java baseentity_hibernate 配置文件 和一个 id生成类BaseEntity.java 和一个hibernate工具类 HibernatUtils.java...

package com;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

import com.entity.Food;

import com.entity.Husband;

import com.entity.User;

import com.entity.Wife;

import com.entity.student.Classes;

import com.entity.student.Teacher;

public class Test1 {

private Session s;

private Transaction tran;

@Before

public void before(){

s=HibernateUtils.getSession();

tran=s.beginTransaction();

}

public void test(){

User user=(User)s.get(User.class,7);

//持久太

//user.setUsername("xixixi");

//修改后不用save直接提交也可保存

tran.commit();

s.clear();//使对象与session没有关系 , 脱离持久太

//把游离态的user变成持久态

tran=s.beginTransaction();

s.update(user);

user.setPassword("789");

tran.commit();

//将对象变成顺时太

tran=s.beginTransaction();

s.delete(user);

tran.commit();

}

public void one2one(){

Husband h=new Husband();

Wife w=new Wife();

//创建两个瞬时对象

h.setName("xiaoming");

w.setName("baby");

w.setHusband(h);

s.save(w);

s.save(h);

}

@Test

public void one2oneQuery(){

Husband h=(Husband)s.get(Husband.class, 2);

System.out.println(h.getName()+"-------------"+h.getWife().getName());

}

@After

public void after(){

tran.commit();

HibernateUtils.closeSession(s);

}

hibernate.cfg.xml

package com.entity;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.MappedSuperclass;

@MappedSuperclass

public class BaseEntity {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

private Integer id;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

}

BaseEntity.java

package com;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtils {

private static SessionFactory sf;

static{

Configuration cfg=new Configuration().configure();

//在根目录src下括号内路径可以省略

//Configuration cfg=new Configuration().configure("/hibernate.cfg.xml");

//读取配置文件

sf=cfg.buildSessionFactory();

}

//构造会话工厂

public static Session getSession(){

return sf.openSession();

}

//得到会话

public static void closeSession(Session session){

if(session!=null){

session.close();

}

}

//关闭会话

}

hibernateutils.java

用来读取配置文件,生成会话

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值