我有两个表(即 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
这里出了什么问题?我将 TableTwo
内 TableOne
的 transient 对象转换为持久状态,然后持久化 TableTwo
对象。我该如何纠正这个问题?如果可能的话,是否可以通过注释来做到这一点?
我不想每次持久化 TableTwo
对象时都持久化 TableOne
对象。如果可能的话,我只想这样做:
tableTwo.setTableOne(new TableOne(id));
dao.persist(tableTwo);
最佳答案
我发现您正在从服务类获取 tableOne
对象,即 TableOne tableOne = service.getTableOneById(id);
。
因此,我相信 tableOne
记录已存在于数据库中,因此无需在您的 dao insert(...)
方法中再次保留它。
您可以删除 sessionFactory.getCurrentSession().persist(tableTwo.getTableOne());
,因为您没有对 tableOne
对象进行任何更改。
或者,如果您对需要保留的 tableOne
对象进行了任何更改,请考虑使用合并方法,即 sessionFactory.getCurrentSession().merge(tableTwo.getTableOne( ));
相反。
关于java - 方法抛出 'org.hibernate.PersistentObjectException' 异常。分离的实体传递到持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952361/