我有
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Linf getLinf() {
return linf;
}
和
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = MessageEntry.class)
public Set<MessageEntry> getMessageEntries() {
return messageEntries;
}
我需要从数据库中删除单个 messageEntry。如果我说 sess.delete(messageEntry),那么我会得到索引异常,因为它在 Linf.messageEntries 集合中。无状态会话无法加载集合,因此我必须手动加载 Linf.messageEntries 的元素,然后删除其中一个:
List linfs = sess.createQuery(
"SELECT l FROM Linf l " +
"JOIN l.messageEntries e WHERE e=:e")
.setParameter("e", messageEntry).list();
if (linfs.size()>1) throw new RuntimeException();
Linf linf = (Linf) linfs.get(0);
List<MessageEntry> curEntries =
sess.createQuery(
"SELECT e FROM Linf l " +
"JOIN l.messageEntries e WHERE l=:l")
.setParameter("l", linf).list();
for (int i = 0; i < curEntries.size(); i++) {
if (curEntries.get(i).getId().equals(messageEntry.getId())) {
curEntries.remove(i);
break;
}
}
Set<MessageEntry> cur = new HashSet<MessageEntry>();
cur.addAll(curEntries);
linf.setMessageEntries(cur);
messageEntry.setLinf(null);
sess.update(messageEntry);
sess.update(linf);
sess.delete(messageEntry);
我得到 ConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint failed ( db
. linf_messageentry
, CONSTRAINT FK5039A8B5E770809A
FOREIGN KEY ( messageEntries_id
) REFERENCES messageentry
( id
))。我该如何执行此任务?谢谢你。