标签:blog io os ar java for sp div on
package com.entity; import javax.persistence.Entity; import javax.persistence.OneToOne; @Entity public class Husband extends BaseEntity { @OneToOne(mappedBy = "husband") private Wife wife; public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
husband.java
package com.entity; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Wife extends BaseEntity { private String name; @ManyToOne @JoinColumn(name="husband_id",unique=true) private Husband husband; public String getName() { return name; } public void setName(String name) { this.name = name; } public Husband getHusband() { return husband; } public void setHusband(Husband husband) { this.husband = husband; } }
wife.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); } }
test1.java
标签:blog io os ar java for sp div on
原文地址:http://www.cnblogs.com/tianhao/p/4022879.html