About this question
What is meant by a detached entity passed to persist? There is a JPA-persisted object structure that has many-to-one relation: The single account has various transactions while a transaction contains a single account. The code is given below:
@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 transactions;
It is possible to make an ACcount object, include transactions, and persist the account object properly. However, on making the transaction, utilizing a previously present persisted account, and persisting the transaction, there’s an exception like the one below:
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.paulsanwald.Account at org.hibernate.
Hence. It’s possible to persist the account that has transactions, but not the transaction having an account. I wondered if this was due to the account not being attached, however I am receiving the same exception yet.
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);
What is the way to properly save transactions, linked with a previously persisted account object?