JPA Fetch Update Save

Context

Enterprise applications use libraries that manage persistence. These libraries allow a developer to express persistence in the language they are programming with without a need to use the language of the database, which in most cases is SQL. In Java ecosystem, libraries like Hibernate and MyBatis cropped up. JPA captures the common elements across the various libraries like hibernate and MyBatis and enables expression of persistence elements as annotations. Spring provides a JPA implementation

Fetch update save problem – logical view:

On fetch of a row from database, hibernate creates an object that it tracks, lets call it managed object. Once this is done, you can perform any operation on the object. Once done, you would have to save the object back again into the database to persist your changes. This leads to a curious condition. The object and the row exist in different memory space. Which means that the integrity of representation can be violated by operations on either of them.

One solution to the problem is to synchronize the updates between the row and the object. You open a session, fetch an object, modify it and save it back before closing the session. In hibernate terminology, such an object is called persistent object. One problem with this approach is that the operation on the object has to be fast as a session to the database is a bottleneck for performance.

To overcome this, hibernate allows us to detach an object from the session, make modifications to it and merge it back to a session, there by preventing the need to keep a session open throughout the transaction. This can be bit tricky as the hibernate needs to manage the conflicts between the detached object and the object in the session. Some scenarios are listed here.

Of course. Spring JPA abstracts all this from the developer.

Lesson learnt: ORM is a potential mine field

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s