Reputation: 26713
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?
Upvotes: 2
Views: 2089
Reputation: 691765
load
and get
return the object from the session if it's already there. Your second option would thus need you to flush, then remove the entity from the session, then reload it (issuing a select query for data you know). A call to refresh would do the same, more easily, but would still issue an additional select query for nothing.
I really prefer the first option : just make sure that each time the association is set, then the corresponding mapped property is mapped as well. You're responsible for the coherence and invariants of the entities (as with bidirectional associations, where both sides must be maintained).
A third option would be to remove the mapped property completely, and simply call entity.getKey().getSomeRef().getId().
Upvotes: 1
Reputation: 242706
When you need to refresh state of the object from the database, use refresh()
.
Upvotes: 3