package cn.edu.hpu.one2many; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="m_user") public class User { private int id; private String name; private Group group; //只要有双向就要指定制定一个属性(mapedby) //不指定的话会有两个相同的字段产生 @ManyToOne public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package cn.edu.hpu.one2many; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="m_group") public class Group { private int id; private String name; private Set<User> users=new HashSet<User>(); //选择set的原因是因为,set互相之间不会有重复的 //跟数据库模型比较匹配 @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(mappedBy="group") public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
@Test public void testSaveUser(){ User u=new User(); u.setName("u1"); Group g=new Group(); g.setName("g1"); sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory(); Session s=sessionFactory.openSession(); s.beginTransaction(); s.save(g); s.save(u); s.getTransaction().commit(); }
User u=new User(); u.setName("u1"); Group g=new Group(); g.setName("g1"); u.setGroup(g);//给user设定group
@ManyToOne(cascade={CascadeType.ALL}) public Group getGroup() { return group; }
User u=new User(); u.setName("u1"); Group g=new Group(); g.setName("g1"); u.setGroup(g);//给user设定group sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory(); Session s=sessionFactory.openSession(); s.beginTransaction(); //s.save(g);没有存group s.save(u); s.getTransaction().commit();
但是有一点要注意:我们最开始的那个实验,我们完全可以手动去写,所以cascade只是让编程更加方便,而不是我们非要用的东西。如果你关联关系理解的比较复杂,你就用手动去写就可以,不一定非要用csacade。
转载请注明出处:http://blog.csdn.net/acmman