简体   繁体   中英

jpa cascade persist many to one

I have two JPA entities (Account and Person), with a bidirectional relationship:

@Entity
@Table(name = "ACCOUNTS")
@DataCache(enabled = false)
public class Account
{
    ....
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "ID_OWNER", nullable = false)
    private Person owner;
    ...
}

@Entity
@Table(name = "OWNERS")
@DataCache(enabled = false)
public class Person {
    ...
    @Column(name = "HAS_ACCOUNTS", nullable = false, columnDefinition = "CHAR(1)")
    private char hasAccounts;

    @OneToMany(mappedBy = "owner")
    private Set<Accpunt> comments = new LinkedHashSet<Account>(3);
    ...
}

When I persist a Person, I do not want to persist all the accounts, but when I persist an account, I want to update the person property hasAccounts, so I need to also update the person.

I make the following steps:

  • create a Person
  • persist the person
  • create an Account
  • modify the owner (the previously created
  • persist the account (and I hope that it automatically merges the Person)
Person p = new Person();
em.persist(p);
Account a = new Account();
a.setOwner(p);
p.setHasAccounts('Y');
em.persist(a);

and I get this exception:

   javax.ejb.EJBTransactionRolledbackException: org.hibernate.PersistentObjectException: detached entity passed to persist: Person

(I use JPA 1.0 with Hibernate).

Try the following:

Person p = new Person();
Account a = new Account();

p.getComments().add(a);
p.setHasAccounts('Y');

em.persist(p);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM