0

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).

MichelReap
  • 5,630
  • 11
  • 37
  • 99

1 Answers1

0

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

i.e. 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

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110