PersistentObjectException:由 JPA 和 Hibernate 传递给 persist 的分离实体
我有一个JPA持久化的对象模型,它包含一个多对一的关系:an有很多。A 有一个 。Account
Transactions
Transaction
Account
下面是代码片段:
@Entity
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
private Account fromAccount;
....
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(cascade = {CascadeType.ALL},fetch= FetchType.EAGER, mappedBy = "fromAccount")
private Set<Transaction> transactions;
我能够创建一个对象,向其添加事务,并正确保留该对象。但是,当我使用现有的已持久化帐户创建事务并持久化事务时,我得到一个异常:Account
Account
Caused by: org.hibernate.PersistentObjectException: de detached entity pass to persist: com.paulsanwald.Account at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:141)
因此,我能够持久保存一个包含事务的事务,但不能持久保存具有 .我以为这是因为可能没有附加,但这段代码仍然给了我同样的例外:Account
Account
Account
if (account.getId()!=null) {
account = entityManager.merge(account);
}
Transaction transaction = new Transaction(account,"other stuff");
// the below fails with a "detached entity" message. why?
entityManager.persist(transaction);
如何正确保存与已持久化对象关联的 .Transaction
Account