我有两个实体bean,它们之间的联接表如下
@SuppressWarnings("serial")
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.employee")
@Cascade(value = { org.hibernate.annotations.CascadeType.ALL,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
@Fetch(FetchMode.SELECT)
private Set<EmployeeGroup> employeeGroups = new HashSet<EmployeeGroup>();
}
和
@SuppressWarnings("serial")
@Entity
@Table(name = "messaginggroup", uniqueConstraints = { @UniqueConstraint(columnNames = "group_name") })
public class MessagingGroup implements Serializable {
@OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.messaginggroup")
@Cascade(value = { org.hibernate.annotations.CascadeType.ALL,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
@Fetch(FetchMode.SELECT)
private Set<EmployeeGroup> employeeGroups = new HashSet<EmployeeGroup>();
}
和
@SuppressWarnings("serial")
@Entity
@Table(name = "employee_group")
@AssociationOverrides(value = {
@AssociationOverride(name = "pk.messaginggroup", joinColumns = @JoinColumn(referencedColumnName = "group_id")),
@AssociationOverride(name = "pk.employee", joinColumns = @JoinColumn(referencedColumnName = "employee_id")) })
public class EmployeeGroup implements Serializable {
@EmbeddedId
private EmployeeGroupId pk = new EmployeeGroupId();
}
使用我的联接表添加和删除时,我使用
public void updateMsgGroup() {
try {
log.debug("### Updating Messaging Group ##### ");
MessagingGroup msgGroup = msgGroupServ.getMsgGroupByID(Long
.parseLong(selectedmsgGroup));
msgGroup.setGroupName(this.catchedGroupName);
Set<EmployeeGroup> mySet = msgGroup.getEmployeeGroups();
for (EmployeeGroup mepGrop : mySet) {
msgGroupServ.deleteEmpMsgGroup(mepGrop);
}
// msgGroup.getEmployeeGroups().clear();
Set<EmployeeGroup> amySet = new HashSet<EmployeeGroup>();
for (Employee newEmp : this.currentRelatedEmp) {
EmployeeGroup empGrp = new EmployeeGroup();
empGrp.setEmployee(newEmp);
empGrp.setMessageGroup(msgGroup);
empGrp.setJoinType(true);
msgGroup.getEmployeeGroups().add(empGrp);
amySet.add(empGrp);
// empGroupsList.add(empGrp);
}
log.debug(" $$$$ Set Size $$$$ " + mySet.size());
// msgGroup.setEmployeeGroups(mySet);
msgGroupServ.updateMsgGroup(msgGroup);
} catch (Exception e) {
e.printStackTrace();
}
}
为什么将
CascadeType
设置为CascadeType.REMOVE
我可以删除但无法添加
并将其设置为
CascadeType.All
我可以添加但不能从数据库中删除
那么我如何解决这个问题的任何想法?
最佳答案
尝试这个:
@Cascade(value = { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE
org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
SAVE_UPDATE =用于添加和更新元素的级联;
ALL =级联仅添加
那么你也必须定义DELETE
参考:javadoc