JPA: what is the behavior of merging with lazy initialization sets?

The following is the sequence that caused the problem:

>I have a team record and 3 player records in the database Team entity has one that uses fetchtype LAZY,CascadeType. List of all > click the search button on webui > call the query queried by the server using JPA to find all team records. In this case, query only one record of the team entity returned from the query (including the agent of the player entity list) > map this teamentity to dto and return this dto to webui, skip the mapping of the player entity list > webui presents dto in HTML format, Prepare to receive the user's modification > the user modifies the team's attributes, such as the date of team establishment > click the Save button on webui > Convert dto to team entity for updating the existing team record > but in this case, if I want to use em.merge (teamentity), the team record will be updated, but what will happen to the player list? Because when converting from dto to team entity, teamentity has an empty list of player entities After the merge, I noticed that the size of teamentity was 0 But after refreshing the entity em.refresh (teamentity), it will return three detail sizes

I'm confused:

>Why is the size 0 after merging? It's like no longer representing Records > before testing, I think the details will be deleted because I merge teamentity with empty details

Please comment:)

thank you!

Solution

The JPA specification states:

As you can see, there is no magic here The state of the detached instance is copied to the newly created managed instance Since your detached instance has an empty list, the managed instance will also have it

Further behavior depends on the ownership of the relationship, because the representation in the database reflects the owner of the relationship:

>If the team is the owner, the relationship between the team and the player will be destroyed during refresh (but the player will survive unless there is orphanremoval = true in your relationship). > Otherwise, having an empty list in the team will not affect the database

If you refresh the team before refreshing the context, all properties of the team will be overwritten by the values in the database, so the player list will be restored (because the empty list of players has not been refreshed)

If you call flush () before calling refresh (), and Team is the owner, list will be empty, because during flush (), the violation of the relation will propagate to the database.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>