Search code examples
javahibernatejpaormseam

Get both the current modified entity and the database entity snapshot with Hibernate


We use seam as Java EE framework. I've controller which inherits from EntityHome. When user press 'Save' button, we have a modified entity instance, but not flushed this changes to database.

How can I retrieve this entity in two states(1st - database state, 2-nd user modified state)?

I've tried to use enityManager.refresh(object), but it's also reset all changes in user modified state of object.

I think about two sessions, but i wonder, if there is a better solution?


Solution

  • You can do it like this:

    1. You clone the currently attached entity, using a deep-copy serialization/deserialization (that means all your entities should be serialable):

      MyEntity clonedObject = org.apache.commons.lang3.SerializationUtils.clone(object);
      
    2. Then you refresh the currently attached object:

      session.refresh(object);
      

    Now you have both the modified object (e.g. clonedObject) and the original entity version (e.g. object).

    If you want to merge the clonedObject, you can simply do it like this:

    object = session.merge(clonedObject);