package cn.edu.hpu.one2many;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
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.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="m_group")
public class Group {
private int id;
private String name;
private Set users=new HashSet();
//选择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",
cascade={CascadeType.ALL},
fetch=FetchType.LAZY
)
public Set getUsers() {
return users;
}
public void setUsers(Set users) {
this.users = users;
}
}
@Test
public void testUpdateUser(){
sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Session s=sessionFactory.openSession();
s.beginTransaction();
User u=(User)s.load(User.class,2);
u.setName("user22");
u.getGroup().setName("gggg");
//load取出的只是对象的代理,用user的时候才会发出sql语句去取
//很显然后面用到了,所以它发出sql语句去取了。当commit()的时候会查看
//user在缓存中是否和数据库中的数据一样,不一样的话它会去修改数据库
//中的值,此时会发出update的语句,和直接update的效果一样。
s.getTransaction().commit();
}
@Test
public void testUpdateUser(){
sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Session s=sessionFactory.openSession();
s.beginTransaction();
User u=(User)s.load(User.class,3);
s.getTransaction().commit();
u.setName("userTom");
u.getGroup().setName("gTom");
s.beginTransaction();
s.update(u);
s.getTransaction().commit();
}
其实最简单的就是设ALL就行了。
尊重开源精神,尊重劳动成果,转载请注明出处:http://blog.csdn.net/acmman/article/details/43889457