Skip to content
Advertisement

Spring Data Jpa: persisting child entities from parent entity does not update child identity

Environment:

  • OS: Ubuntu 20.04 LTS
  • Java: OpenJDK 17.0.3
  • Spring Boot: 2.6.7
  • MySQL: 8.0.29

Is it normal for Spring Data Jpa (or Jpa in general) to NOT update child identity attributes when the child is persisted (saved) via the parent entity repository?

Consider this:

JavaScript

When I call someClassFunction() I get:

JavaScript

The database assigned id is NOT available to me immediately. I did check the database and the record was inserted (persisted/saved) and MySQL did assign an ID. If I reload the parent class (company) in another function, the child is reloaded and has the correct id.

However, if I modify someClassFunction() to this:

JavaScript

and then call someClassFunction() I get:

JavaScript

The database assigned id is available to me immediately.

I don’t find the parent/child persist (ie: this.companyRespository.save( company ) ) behavior disclosed in any online documentation or tutorials. I am led to believe that persisting from the parent should work the same as persisting the child directly ( ie: this.phoneRespository.save( phone ) ).

Am I doing something wrong? Do I have an incorrect entity definition?

Advertisement

Answer

Yes, this is expected – check the contract on your ‘save’ method. It returns an instance which may be a copy of the one you passed in, and it is this instance you need to check and use – it will have its identity set when the entityManager is synchronized with the database (on transaction commit, or if the EntityManager is flushed).

ie

JavaScript

Spring does some internal checks in the save method to determine if it should call JPA EntityManager merge or persist api. If it calls merge, it returns the managed entity instance from the context (which may be a clone of the one you give it) while if it calls persist, it takes your instance and causes it to become managed. It is the managed instance that is returned on any findById and query methods.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement