![](/img/trans.png)
[英]How to delete row using JPA while keeping the database in a consistent state
[英]JPA does not delete database row
我正面臨着JPA的刪除問題,這是我的代碼:
public deleteLine(int idLine) {
Line line = em.find(Line.class,idLine);
Header header = line.getHeader();
this.deleteLine(header,line);
}
public boolean deleteLine(Header header, Line line) {
try {
line.setIdArticle(null);
line.setDetail(DELETED_TAG);
line.setQuantity(0.0f);
em.merge(line);
header.getLineCollection().remove(line);
em.remove(line);
em.flush();
}
catch (Exception ex) {
LOG.log(Level.SEVERE, null, ex);
}
return true;
}
當我調用deleteLine()
,我以idArticle
為null
的數據庫行結束,詳細信息等於DELETED_TAG
常量, quantity
等於0
。 但是,盡管em.remove
,行仍然存在。
我試圖在刪除之前添加一個line.setHeader(null)
,但是我得到一個ConstraintViolationException
因為header字段不能為null
。
顯然我做錯了什么,但我無法弄清楚是什么。
有實體代碼:
public class Header implements Serializable {
[...]
@OneToMany(cascade = CascadeType.ALL, mappedBy = "header")
private Collection<Line> lineCollection;
[...]
}
public class Line implements Serializable {
[...]
@JoinColumn(name = "header", referencedColumnName = "header")
@ManyToOne(optional = false)
private Header header;
[...]
}
我已經完成了通過JPQL( DELETE FROM Linea WHERE idLinea=?
)刪除行的測試,並且它有效地刪除了該行。 但是,當JPA執行提交時,由於JPA執行了INSERT
,該行重新出現。
有沒有辦法發現原因? 顯然,有一個生成插入的實體,但我正在從標題中刪除該行,那么我該怎么做才能找出觸發插入的內容?
我弄清楚問題出在哪里:當用戶刪除一行時,我就是這樣做的
由於jpa如何工作,對頭字段的修改迫使jpa跳過刪除子節點(因為所有級聯)或重新插入它,因為實際上,實體仍然存在並且休眠“行走”並重建父子樹。
對於遇到相同問題的人,如果要刪除子項並在刪除后更新父項,我找到的正確方法是:
對我來說,按照這個確切的順序做事就解決了這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.