牵扯到对一个实体对象做操作,是否要对关联的另外一个实体对象做操作。
这里来探讨一下删除delete“多对一”中“多”这一方的问题:
User.java:
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.EAGER) 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; } }
Group.java:
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<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", cascade={CascadeType.ALL}, fetch=FetchType.LAZY ) public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
删除多那一方的测试代码:
@Test public void testDeleteGroup(){ sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory(); Session s=sessionFactory.openSession(); s.beginTransaction(); Group g=(Group)s.load(Group.class,4); s.delete(g); s.getTransaction().commit(); }
输出的sql语句:
Hibernate:
select
group0_.id as id0_0_,
group0_.name as name0_0_
from
m_group group0_
where
group0_.id=?
Hibernate:
select
users0_.group_id as group3_0_1_,
users0_.id as id1_,
users0_.id as id1_0_,
users0_.group_id as group3_1_0_,
users0_.name as name1_0_
from
m_user users0_
where
users0_.group_id=?
Hibernate:
delete
from
m_user
where
id=?
Hibernate:
delete
from
m_user
where
id=?
Hibernate:
delete
from
m_group
where
id=?
说明把与group关联的user全部删除了(u3和u4都是关联g4的,全被删)。原因是因设置了cascade={CascadeType.ALL}。
如果不想删除关联的u3和u4怎么办呢?
很简单,还是将关联去除(将group的user全部提取出来,去除关联关系,即group设置为null,),然后在删除即可。(但是u3、u4就变成了“垃圾数据”)建议把关联的也删除,根据情况而定了(一般都是根删除,孩子也删除)。
觉得难控制,自己写HQL语句就行了。
尊重开源精神,尊重劳动成果,转载请注明出处:http://blog.csdn.net/acmman/article/details/43889447