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
用来读取配置文件,生成会话