[英]Problems in hibernate CascadeType
我有兩個實體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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.