views:

13

answers:

0

I am storing a relatively complex immutable object in a database. There are many many-to-one associations - the object has properties that have properties and so on.

I would like to have each object stored only once, based on a business key that is in this case every single property of the object.

The workflow is like this:

  • user creates a complex object. This can take a long time, code is all scattered over the place.
  • I query the database, to see if the exact same object was already stored before:
    • if not, save
    • if yes, set the object's id and merge

The problem is that Hibernate's merge has quite inconvenient semantics:

transientObject = createComplexTransientObject();
mergedObject = session.merge(transientObject);
// here you have to discard transientObject
// use mergedObject from now on

The object that got created has to be discarded and replaced with the one provided by Hibernate, which means I have to update all references to it.

I need a way to tell hibernate: "This completely new transientObject appears to be identical to one that is already in the database. Merge it in place." In other words:

object = createComplexTransientObject();
session.inPlaceMerge(object);
// object is now persistent

How can I achieve that?