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

前端 未结 18 2817
醉酒成梦
醉酒成梦 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:39

    You need to set Transaction for every Account.

    foreach(Account account : accounts){
        account.setTransaction(transactionObj);
    }
    

    Or it colud be enough (if appropriate) to set ids to null on many side.

    // list of existing accounts
    List accounts = new ArrayList<>(transactionObj.getAccounts());
    
    foreach(Account account : accounts){
        account.setId(null);
    }
    
    transactionObj.setAccounts(accounts);
    
    // just persist transactionObj using EntityManager merge() method.
    

提交回复
热议问题