I read and tested a lot. The problem arose due to my misunderstanding of JPA / Hibernate. merge () always hits the database, and also plans to update the object. I did not find mention of this in the JPA specification, but the book "Java Persistence with Hibernate" mentions this.
Looking through the EntityManager (and Session as fallback) API, it looks as if there is no way to simply assign an entity to the current persistent context WITHOUT scheduling an update. In the end, I want to move around the graph of objects, changing properties as needed and start updating (with version checking, if necessary) later. Something that I think every Webapp using ORM should do?
The main workflow I'm looking for:
- load an object from the database (or create a new one)
- let the entity (and all its associations become disconnected (since the EntitManager closes at the end of the HTTP request)
- when the next HTTP request arrives, work with these objects again, moving the tree without fear of LazyInitExceptions
- calling a method that saves all changes made within 1-3)
With the OSIV filter from spring in combination with the implementation of the IModel from the gate, I thought I archived this.
Basically, I see two possible ways:
a) load the object and all associations necessary when entering a certain page (use case), allowing them to disconnect, adding / changing them as necessary during several HTTP requests. Then reconnect them when the user initiates the save (validators will ensure the correct state) and send them to the database.
b) use the current setting, but make sure that all newly added objects have all the necessary fields (possibly using some components of the wizard). I would still have all the database updates for each merge (), but hopefully the database administrator will not understand;)
How do other people work with JPA in a web environment? Any other options for me?
source share