我有两个表(即,在Hibernate中的实体),它们作为相关:现在方法抛出'org.hibernate.PersistentObjectException'异常。脱离实体被persist
@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
注释的方法(或一类),我称之为服务类方法坚持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
对象。我该如何解决这个问题?如果可能的话,是否可以通过注释来实现?
我不想坚持TableOne
对象每次我坚持TableTwo
对象。如果可能的话,我只想做:
tableTwo.setTableOne(new TableOne(id));
dao.persist(tableTwo);
您是否尝试将'cascade'属性添加到'ManyToOne(fetch = FetchType.EAGER)'中。这样您就不需要明确保存tableone实体。 –
哪个级联属性:ALL,PERSIST,MERGE,REMOVE,REFRESH,DETACH? – OneMoreError
由于您正在调用persist方法,请确保级联属性为PERSIST或ALL。 –