![](/img/trans.png)
[英]org.hibernate.PersistentObjectException: detached entity passed to persist exception
[英]Method threw 'org.hibernate.PersistentObjectException' exception. detached entity passed to persist
我有兩個表(即,Hibernate中的實體),它們相關如下:
@Entity
@Table(name = "table_one")
public class TableOne {
private int id;
private String code;
private String value;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
@Column(name= "code")
public String getCode() {
return this.code;
}
@Column(name= "value")
public String getValue() {
return this.value;
}
// setters ignored here
}
----------------------------------------------
@Entity
@Table(name = "table_two")
public class TableTwo {
private Integer id;
private TableOne tableOne;
private String request;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "table_one_id", nullable = false)
public TableOne getTableOne() {
return tableOne;
}
@Column(name= "request")
public String getRequest() {
return this.request;
}
// setters ignored here
}
現在,從沒有@Transactional
批注的方法(或類)中,我調用Service類方法來保留TableTwo
對象。 該服務方法@Transactional
注釋。
// from a normal method with no annotations
service.insert(tableTwo);
----------------------------
public class MyService {
@Autowired
private MyDao dao;
@Transactional
public void insert(TableTwo tableTwo){
dao.insert(tableTwo);
}
}
------------------------------
public class MyDao {
public void insert(TableTwo tableTwo){
sessionFactory.getCurrentSession().persist(tableTwo.getTableOne());
sessionFactory.getCurrentSession().persist(tabletwo);
}
}
這給了我以下調試異常:
Method threw 'org.hibernate.PersistentObjectException' exception.
detached entity passed to persist: org.project.TableOne
這是怎么了 我將TableOne
內的TableTwo
的瞬態對象轉換為持久狀態,然后將TableTwo
對象持久TableTwo
。 我該如何糾正? 如果可能的話,可以通過注釋嗎?
我不希望被持續TableOne
我每次持續時間對象TableTwo
對象。 如果可能,我只想做:
tableTwo.setTableOne(new TableOne(id));
dao.persist(tableTwo);
嘗試調用saveOrUpdate
而不是persist
。
persist
操作適用於全新的臨時對象,如果已分配id
則它將失敗。
我看到您正在從服務類中獲取tableOne
對象,即TableOne tableOne = service.getTableOneById(id);
。
因此,我相信tableOne
記錄已存在於數據庫中,因此以后無需再次將其持久保存在dao insert(...)
方法中。
您可以刪除sessionFactory.getCurrentSession().persist(tableTwo.getTableOne());
因為您沒有對tableOne
對象進行任何更改。
或者,如果您需要tableOne
對tableOne
對象的任何更改,請考慮使用合並方法,即sessionFactory.getCurrentSession().merge(tableTwo.getTableOne());
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.