![](/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.