简体   繁体   中英

Hibernate update with relations foreign key

I am trying to persist entity A which has a reference to a B object, with Hibernate through JPA.

In my view, I created a form which has a combobox filled with B entries. When I process user's input I create a new DTO for A element and I assign a B DTO as its related entity.

Then I send this object to my service layer and there I call my dao to persist my A entity:

dao.persist(A);

But I get the following exception:

Error org.hibernate.TransientPropertyValueException: object references an unsaved transient instance

If I annotate my Entity with cascade=CascadeType.ALL , then I get a new B entity inserted into the database.

How can I do it so my A entity is persisted just by the foreign key for B? That is, only the foreign key gets inserted into the database (since B is a master table, I don't need elements to be inserted).

You need to set both side of the relationship to have cascading handled properly in a bi-directional relationship.

ie for onetotone:

a.setB(b);
b.setA(b);

onetomany:

a.setB(b);
b.getAs().add(a);

Please see here for how you should encapsulate these operations:

https://stackoverflow.com/a/23648953/1356423

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