Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

How To Solve The Issue Jpa/Hibernate: Detached Entity Passed To Persist?

Asked by Dan Peters Aug 2, 2023 2.4K views 1 answer
Share

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?


Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.