skuntsel
skuntsel

Reputation: 11742

How to force Hibernate not to propagate changes to database on change of one of its entities

Hibernate is very useful for a handful of things. But a trivial thing stays out of attention focus. I want to provide for a way of modifying the database entries in an 'admin panel'. To be more specific, I want to have a view with the ability to modify say, a product, its properties, its images, its prices etc. For this reason I load an edit view of product to be modified via, for example, session.get(Product.class, id). I then work with its properties, modify names, set prices, load images and do anything else I want. But finally a user must decide whether or not to save changes or discard them. Saving part is easy - call session.save withing a transaction in service layer, but discarding seems to be a harder issue, because any subsequent session flush will propagate the cancelled changes in product to the database.

So, my question is how to set up such a scheme. What is the best bet for this? I personally see the following solutions:

  1. Call session.evict() with cascade or
  2. Use some replicated copy / DTO and merge on save action or
  3. Process all changes on the client then populate the hibernate entity back on save.

Upvotes: 2

Views: 2623

Answers (1)

skuntsel
skuntsel

Reputation: 11742

Actually I messed up the basic hibernate functioning which stemmed from misunderstanding of hibernate persistence lifecycle.

So, one of the typical approaches taken is splitting up (1) loading an entity by calling dao.load(key) method and detaching it from session by closing the associated session providing user the time to deal with it, (2) modifying a detached entity in the presentation layer by a user and (3) later reattaching the detached object to a new session making it persistent again and, if necessary, by merging it, calling dao.merge(object). Of course, one may use a DTO not to interfere with different program layers.

Another approach that is also sensible consists of dealing with persistent object within one session, or transaction, in which case cancelling changes can be simply made either by evicting the object from session, session.evict(), or by rolling back the complete transaction, transaction.rollback().

In case anyone like me encounters such a misunderstanding my reference list will be:

  1. Hibernate documentation on object states;
  2. Hibernate documentation on persistence contexts or
  3. A good hibernate review presentation on slidreshare.

Upvotes: 3

Related Questions