Here are the sequences leading to the question :
- I have a Team record, and 3 Player records in the database. Team entity has a List that is using FetchType.LAZY, CascadeType.ALL
- The search button on the webui is clicked
- Query in the server side using JPA query is invoked, finding all the Team records, in this case, only 1 record of the team entity returned from the query (which has a proxy of the list of player entities)
- Map this teamEntity to a DTO, and return this DTO to the webui, skipping the mapping of the list of player entities
- Webui renders the DTO in a html form, ready to receive modifications from the user
- User modifies the team’s properties, like the date of when it’s founded
- The save button on the webui is clicked
- Converting the DTO to the team entity, to be used to update the already existing team record
- But in this case, if i were to use the em.merge(teamEntity), the team record will be updated, but what will happen to the list of players ? Because when converting from DTO to the team entity, the teamEntity has an empty list of players entities. And after merging, i notice that the teamEntity has 0 size of the details. But after refreshing that entity, em.refresh(teamEntity), it will return 3 of the detail size.
Im confused on :
- Why is it the size is 0 after merged ? It’s like not representing the record anymore
- Before doing the test, i was thinking that the details will be removed since im merging a teamEntity with an empty detail.
Please enlighten me 🙂
Thank you !
JPA Specification says:
As you can see, there is no magic here. The state of detached instance is copied into the newly created managed instance. Since your detached instance has an empty list, managed instance would have it too.
Further behaviour depends on ownership of relationship, since representation in the database reflects the owning side of relationship:
Teamis the owning side, relationships betweenTeamandPlayers will be destroyed during flush (butPlayeritself would survive unless you haveorphanRemoval = trueon your relationship).Teamdoesn’t affect the database.If you refresh the
Teambefore flushing the context, all properties ofTeamare rewritten by values from the database, therefore list ofPlayers is restored (since the empty list of players wasn’t flushed yet).If you call
flush()before callingrefresh(), andTeamis the owning side, list will be empty, since destruction of relationships was propagated to the database duringflush().