我和CohortGroup和员工有很多关系。每当我将一个Employee插入CohortGroup时,hibernate都会从分辨率表中删除该组,并再次插入所有成员,再加上新成员。为什么不添加新的?
小组中的注释:
@ManyToMany(cascade = { PERSIST, MERGE, REFRESH })
@JoinTable(name="MYSITE_RES_COHORT_GROUP_STAFF",
joinColumns={@JoinColumn(name="COHORT_GROUPID")},
inverseJoinColumns={@JoinColumn(name="USERID")})
public List<Employee> getMembers(){
return members;
}
员工的另一面
@ManyToMany(mappedBy="members",cascade = { PERSIST, MERGE, REFRESH } )
public List<CohortGroup> getMemberGroups(){
return memberGroups;
}
代码片段
Employee emp = edao.findByID(cohortId);
CohortGroup group = cgdao.findByID(Long.decode(groupId));
group.getMembers().add(emp);
cgdao.persist(group);
下面是日志中报告的sql
delete from swas.MYSITE_RES_COHORT_GROUP_STAFF where COHORT_GROUPID=?
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
这种接缝效率非常低,并且会导致一些问题。如果要求将一名员工添加到该组中,则会有一些人过来书面。
像equals和hashCode这样的接缝可能就是这个原因。以下是这些方法的实现。有没有红旗?
CohortGroup
@Override
public int hashCode() {
final int prime = 31;
int result = getName().hashCode();
result = prime * result + ((emp == null) ? 0 : emp.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {return true;}
if (!(obj instanceof CohortGroup)) {return false;}
CohortGroup other = (CohortGroup) obj;
if(!getName().equals(other.getName())){return false;}
if (emp == null && other.getOwner() != null) {
return false;
} else if (!emp.equals(other.getOwner())) {
return false;
}
return true;
}
员工
@Override
public boolean equals(Object obj) {
if (this == obj) {return true;}
if (obj == null) {return false;}
if (!(obj instanceof Employee)) {return false;}
Employee other = (Employee) obj;
if (EMPLID == null && other.getEMPLID() != null) {
return false;
} else if (!EMPLID.equals(other.getEMPLID())) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((EMPLID == null) ? 0 : EMPLID.hashCode());
return result;
}
我已向CohortGroup添加了addMember方法,该方法会添加到关系的两端:
public void addMember(Employee emp){
this.getMembers().add(emp);
emp.getMemberGroups().add(this);
}
继续感谢所有有帮助的人。
答案 0 :(得分:7)
我非常怀疑你没有正确地覆盖equals
和hashCode
。错误地覆盖它们会导致您遇到的行为(因为散列键用作映射中的键)。仔细检查您对equals
和hashCode
所做的工作。
使用带有好equals
和hashCode
的您的带注释的实体,此代码(逻辑上等效):
Session session = HibernateUtil.beginTransaction();
Employee emp = (Employee) session.load(Employee.class, 1L);
CohortGroup group = (CohortGroup) session.load(CohortGroup.class, 1L);
group.getMembers().add(emp);
emp.getMemberGroup().add(group); // set the other side too!!
session.saveOrUpdate(group);
HibernateUtil.commitTransaction();
在我的机器上产生以下输出:
08:10:32.426 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades 08:10:32.431 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections 08:10:32.432 [main] DEBUG org.hibernate.engine.CollectionEntry - Collection dirty: [com.stackoverflow.q2649145.CohortGroup.members#1] 08:10:32.432 [main] DEBUG org.hibernate.engine.CollectionEntry - Collection dirty: [com.stackoverflow.q2649145.Employee.memberGroup#1] 08:10:32.443 [main] DEBUG org.hibernate.engine.Collections - Collection found: [com.stackoverflow.q2649145.CohortGroup.members#1], was: [com.stackoverflow.q2649145.CohortGroup.members#1] (initialized) 08:10:32.448 [main] DEBUG org.hibernate.engine.Collections - Collection found: [com.stackoverflow.q2649145.Employee.memberGroup#1], was: [com.stackoverflow.q2649145.Employee.memberGroup#1] (uninitialized) 08:10:32.460 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 insertions, 0 updates, 0 deletions to 2 objects 08:10:32.461 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 (re)creations, 2 updates, 0 removals to 2 collections 08:10:32.463 [main] DEBUG org.hibernate.pretty.Printer - listing entities: 08:10:32.473 [main] DEBUG org.hibernate.pretty.Printer - com.stackoverflow.q2649145.CohortGroup{id=1, members=[com.stackoverflow.q2649145.Employee#1]} 08:10:32.474 [main] DEBUG org.hibernate.pretty.Printer - com.stackoverflow.q2649145.Employee{id=1, memberGroup=} 08:10:32.474 [main] DEBUG o.h.p.c.AbstractCollectionPersister - Inserting collection: [com.stackoverflow.q2649145.CohortGroup.members#1] 08:10:32.480 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) 08:10:32.491 [main] DEBUG org.hibernate.SQL - insert into MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?) Hibernate: insert into MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?) 08:10:32.496 [main] TRACE org.hibernate.type.LongType - binding '1' to parameter: 1 08:10:32.497 [main] TRACE org.hibernate.type.LongType - binding '1' to parameter: 2 08:10:32.499 [main] DEBUG o.h.p.c.AbstractCollectionPersister - done inserting collection: 1 rows inserted
插入前没有删除!
顺便说一句,请注意,在处理双向关联时,您应该在两个方面设置链接,就像我在员工的和组中所做的那样。
或者在您的课程中添加防御性链接管理方法,例如CohortGroup
:
public void addToMembers(Employee emp) {
this.getMembers().add(emp);
emp.getMemberGroup().add(this);
}
public void removeFromMembers(Employee emp) {
this.getMembers().remove(emp);
emp.getMemberGroup().remove(this);
}
答案 1 :(得分:5)
我遇到了同样的问题,并且通过一些试验和错误发现,如果我使用Set而不是List作为我的集合,则不会发生删除。令人恼火,因为我正在使用JSF和UI组件只会迭代列表。但它就是。
答案 2 :(得分:1)
正如其他人所说,hashcode
或equals
可能存在问题。
具体来说:Hibernate代理导致您在instaceof
方法中使用的equals
出现问题。这就是坏消息。
答案 3 :(得分:1)
我有同样的问题。我从列表更改为集合。它对我有用。
@ManyToMany(cascade = { PERSIST, MERGE, REFRESH })
@JoinTable(name="MYSITE_RES_COHORT_GROUP_STAFF",
joinColumns={@JoinColumn(name="COHORT_GROUPID")},
inverseJoinColumns={@JoinColumn(name="USERID")})
public Set<Employee> getMembers(){
return members;
}
@ManyToMany(mappedBy="members",cascade = { PERSIST, MERGE, REFRESH } )
public Set<CohortGroup> getMemberGroups(){
return memberGroups;
}
答案 4 :(得分:0)
您必须在hashCode()
和equals()
实体上定义CohortGroup
和Employee
。这可以由IDE自动完成,它可以是主键(有时不是一个好主意),也可以是业务键(最好)。
阅读this article。
答案 5 :(得分:0)
我的插入按照我期望的方式进行。感谢Pascal和z5h,我学到了很多东西。我相信我已经正确实现了hashCode和equals。这从来没有解决过我的问题。相反,我实施了一个中间实体。
以下是我的Employee,CohortGroup和现在的CohortGroupMemeber类中的映射。
员工:
@OneToMany(mappedBy="member")
public List<CohortGroupMember> getMemberGroups(){
return memberGroups;
}
public void setMemberGroups(List<CohortGroupMember> grps){
memberGroups = grps;
}
CohortGroupMember
@ManyToOne
@JoinColumn(name="USERID")
public Employee getMember(){
return emp;
}
public void setMember(Employee e){
emp = e;
}
@ManyToOne
@JoinColumn(name="COHORT_GROUPID")
public CohortGroup getGroup(){
return group;
}
public void setGroup(CohortGroup cg){
group = cg;
}
CohortGroup
@OneToMany(mappedBy="group")
public List<CohortGroupMember> getMembers(){
return members;
}
public void setMembers(List<CohortGroupMember> emps){
members = emps;
}
我所遵循的这本书是Java Persistence with Hibernate第7.2.3节
答案 6 :(得分:0)
在持久性上下文中加载对象,如果存在则调用合并,如果不存在则保存。
Employee emp = new Employee();
//set emp attribute and members.
Session session = ...
Transaction transaction = ...
Employee db = (Employee) session.get(Employee .class,emp.getId());
if(db != null) session.merge(emp);
else session.save(emp);
/*session.saveOrUpdate(emp); This will delete the join table and reinsert entry
again*/
transaction.commit();
session.close();