Assuming the following mappings are provided:
<class name="A" table="a_table">
<id name="id"/>
<many-to-one name="entityB" column="fk_B" not-null="false" unique="true"/>
</class>
<class name="B" table="b_table">
<id name="id"/>
</class>
Java class:
public class A {
private long id;
private B entityB;
// getters and setters skipped
}
Is it possible to change the Hibernate mapping so that foreign key is still enforced and created by Hibernate upon startup, but class A
would look like as the following:
public class A {
private long id;
private long idOfB;
// getters and setters skipped
}
I understand that if I convert <many-to-one...
into a <property...
this would work, but foreign key would not be enforced by the database.
I need to do this because object B
might (or might not) be initialized separately which sometimes causes
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
exceptions to occur when a.getB()
is called. I would prefer to have it as a long idOfB
and load whole object whenever is necessary; this would also make loading of object A
quicker.
I believe my question is very similar to this one, yet the offered solution (to use lazy loading) is not appropriate in my case as even if I call a.getB().getId()
, I'd get LazyInitializationException
whereas if I call a.getIdOfB()
I wouldn't.
Thanks very much in advance.