I have a Hibernate entity which has one or more <many-to-one mappings, e.g.
<hibernate-mapping>
<class name="MyClass" table="my_table">
<cache usage="nonstrict-read-write"/>
<composite-id>
<key-property name="id" length="30"/>
<key-property name="someRef" length="30" column="foreign_key_to_something"/>
</composite-id>
<many-to-one name="mappedProperty" column="foreign_key_to_something" insert="false" update="false"/>
<property name="foo" column="foo"/>
...
</class>
</hibernate-mapping>
I need to create such an entity and get immediate access to mappedProperty after the creation. I can see two approaches here:
1) Create the entity and set all related <many-to-one mappings manually. The obvious disadvantage of this approach is the legwork required, especially if the amount of mapped <many-to-one entities is high. Why do something manually if framework can do it for you?
2) Create the entity by only initializing necessary parameters (e.g. primary keys, id and someRef in the above case), then save and re-load it immediately. Loading should initialize the mappedProperty automatically or provide lazy initialization on demand.
I prefer option 2), however, I have noticed that in some cases, mappedProperty property is not set. load() returns the same same object I passed to create(), only having primary keys initialized. I am still not sure why this happens, but to fight it I’d have to detach the object from the Hibernate session so the load() would be forced to go to the database and get anew. Again, sounds quite overcomplicated, doesn’t it?
Am I missing something here? Are there any other ways to solve this problem?
When you need to refresh state of the object from the database, use
refresh().