PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

前端 未结 18 2763
醉酒成梦
醉酒成梦 2020-11-22 05:10

I have a JPA-persisted object model that contains a many-to-one relationship: an Account has many Transactions. A Transaction has one

18条回答
  •  离开以前
    2020-11-22 05:42

    Since this is a very common question, I wrote this article, on which this answer is based on.

    In order to fix the problem you need to follow these steps:

    1. Removing child association cascading

    So, you need to remove the @CascadeType.ALL from the @ManyToOne association. Child entities should not cascade to parent associations. Only parent entities should cascade to child entities.

    @ManyToOne(fetch= FetchType.LAZY)
    

    Notice that I set the fetch attribute to FetchType.LAZY because eager fetching is very bad for performance.

    2. Set both sides of the association

    Whenever you have a bidirectional association, you need to synchronize both sides using addChild and removeChild methods in the parent entity:

    public void addTransaction(Transaction transaction) {
        transcations.add(transaction);
        transaction.setAccount(this);
    }
    
    public void removeTransaction(Transaction transaction) {
        transcations.remove(transaction);
        transaction.setAccount(null);
    }
    

    For more details about why it's important to synchronize both ends of a bidirectional association, check out this article.

提交回复
热议问题