I'm trying to perform get on the session for object which declares composite id without a mapped composite identifier.
Hibernate version used is 3.5.5.
Fetching code is generic and reads container objects wrapping actual data:
ClassMetadata metadata =
session.getSessionFactory().getClassMetadata(wrapper.getDomainClass());
Serializable id = metadata.getIdentifier(wrapper, EntityMode.POJO);
return session.get(wrapper.getDomainClass(), id, LockOptions.UPGRADE);
Code doesn't know anything about actual mapping so it has to consult metadata about the id.
If mapping is defined like:
<hibernate-mapping default-access="field">
<class name="Wrapper"
entity-name="Data"
table="DATA">
<composite-id>
<key-property name="identifier" column="identifier" />
<key-property name="version" column="version" />
</composite-id>
<component name="domainObject" class="Data">
<property name="source" column="source" />
</component>
</class>
</hibernate-mapping>
without composite identifier class, id is equal to the object itself and is equal to wrapper reference.
When I do session.get() instead of fetching object from the database, it returns back same object as was passed in id (not an equal object, but same instance of object).
Upd: In fact session.get() loads object from database in
the id object passed and returns it back. I oversaw that initially thinking it skips loading.
Solution that I found so far is introduce mapped composite identifier and change mapping to:
<hibernate-mapping default-access="field">
<class name="Wrapper"
entity-name="Data1"
table="DATA_1">
<composite-id class="SurrogateKey" mapped="true">
<key-property name="identifier" column="identifier" />
<key-property name="version" column="version" />
</composite-id>
<component name="domainObject" class="Data">
<property name="source" column="source" />
</component>
</class>
</hibernate-mapping>
SurrogateKey is defined as object with two fields and equals/hashcode as required.
With this change id returned by metadata.getIdentifier() is an instance of SurrogateKey and session.get() fetches object from the database if it exists.
The problem with mapping fix is that property names for criteria and HQL change from identifier to id.identifier and that is actually breaking a lot of existing code.
Things I'm exploring at the moment are:
- Is there a way to make session.get() work without declaring Id class (I know this is a discouraged practice, but amount of changes needed might be prohibitive)?
- Could the alternative be telling hibernate to treat properties as before, without adding id. in front of them?
- Upgrade hibernate to v4 (not easy because of dependent projects and approval process)?
- Any other options/workarounds available?
So far I've only managed to make a solution described above work, but I'm searching for less intrusive one and would appreciate any clues, suggestions, pointers to relevant docs.