![](/img/trans.png)
[英]org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
[英]org.hibernate.TransientObjectException: object is an unsaved transient instance - save the transient instance before merging
我知道關於此錯誤有很多問題。 我已經嘗試過了,但沒有解決。
我有一個已經在數據庫中的dtoDevice。 我從數據庫獲得了數據。 現在,我想將dtoValue對象添加到該設備,它不起作用。
我有以下DTO課程
@Entity
public class DtoValue {
@Id
@GeneratedValue
protected int id;
private int value;
@ManyToOne
private DtoDevice dtoDevice;
... /* Getters and Setters */
}
和
@Entity
public class DtoDevice{
@Id
@GeneratedValue
protected int id;
String deviceName;
@OneToMany(cascade= CascadeType.REMOVE)
List<DtoValue> values;
... /* Getters and Setters */
public void addValue(DtoValue dtoValue){
if(dtoValue != null)
values.add(dtoValue);
dtoValue.setDtoDevice(this);
}
}
當我嘗試運行此代碼時:
... /* em = EntityManager */
try{
em.getTransaction().begin();
DtoValue dtoValue = new DtoValue();
dtoValue.setValue(1);
/* Even if I try saving dtoValue here (em.persist/merge(dtoValue)) It doesn't work */
**// THIS dtoDevice is already in the DB - I want to modify it**
dtoDevice.addValue(dtoValue);
/* Even if I try saving dtoValue here (em.persist/merge(dtoValue)) It doesn't work */
/* persist doesnt work, since dtoDevice is already in the DB */
em.merge(dtoDevice);
em.getTransaction().commit();
}
catch(Exception e){
em.getTransaction().rollback();
showConnectionError(e);
}
我得到錯誤:
org.hibernate.TransientObjectException: object is an unsaved transient instance - save the transient instance before merging: **not_important**.model.DtoValue
我嘗試了許多方法,並遵循了一些技巧,直到現在都沒有。
嗨,嘗試先保存DtoDevice,然后將dtoValue設置到DtoDevice,然后再保存DtoDevice。
當您保存DtoDevice時,它具有未保存的DtoValues集合(問題的根源)。 您可以通過幾種方式解決:
1-將PERSIST添加到從DtoDevice到DtoValues的級聯操作列表中,如下所示:
@OneToMany(cascade= {CascadeType.REMOVE, CascadeType.PERSIST})
List<DtoValue> values;
2-保存每個新的DtoValue,然后將其添加到DtoDevice,如下所示:
DtoValue dtoValue = new DtoValue();
dtoValue.setValue(1);
DtoValue savedDtoValue = ... save it here
dtoDevice.addValue(savedDtoValue);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.