I have two classes and tables as defined below:
Code:
class A {
B b;
String name;
getB();
setB();
}
class B {
A a;
getA();
getB();
}
table_a {
id,
name
}
table_b {
id,
a_id (unique)
}
I want to have a one-to-one relationship betwen A and B via the foreign key.
A<-->B
1 0..1
A can have 0 or 1 B, and B must have 1 A.
So the mappings would be thus:
Code:
<hibernate-mapping>
<class name="A" table="table_a">
<id name="id" type="string">
<column name="id" sql-type="CHAR(36)" />
<generator class="native"/>
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<one-to-one name="b" class="B" property-ref="a" cascade="all"/>
</class>
<hibernate-mapping>
<hibernate-mapping>
<class name="B" table="table_b">
<id name="id" type="string">
<column name="id" sql-type="CHAR(36)" />
<generator class="native"/>
</id>
<many-to-one name="a" class="A" column="a_id" unique="true" cascade="none" />
</class>
</hibernate-mapping>
This works perfectly. My question is, however, 'How do I change this mapping so that when querying instances of A, the B instances are NOT also queried?'. i.e. I want to be able to retrieve instances of A via a Session.get() without having the B members returned. (I want to get the Bs later...)
The retrieval code looks like this:
Code:
Session session = sessionFactory.openSession();
trans = session.beginTransaction();
A a = (A)session.get(A.class, aId);
trans.commit();
session.close();
if (a.getB() != null) {
System.out.println("This is bad");
}
I've tried using the lazy="true" attribute of class on both classes for proxying to no avail. I've also tried using various combinations of the outer-join attributes on the associations. Whenever I get A, I always end up getting B as well. In my case, B is a very heavyweight object that only should be retrieved when needed, so this is important (at least to me).
I'm using Hibernate 2.1.2.