Hibernate version: 3.1.2
I just wanted to share a lazy 0 to 1 solution that i've been using. I admit that there must be better solutions out there, but it might be usable by some - and it really takes a few minutes to implement.
You basically set up the mapping files as a one-to-many relationship, set the access as private, and use helper functions to simulate the one-to-one relationship. I haven't done it with two classes with a one-to-one relationship on the primary key, but I assume it will work as well...
For example:
If you have the following entities - Person and Address. A person can have an address, but he/she doesn't have to have one. We want this relationship to be lazy. Hibernate only supports this mode with byte code manipulation - which is fine, but sometimes we don't have that luxury.
In the Person mapping file, we'd set up a one-to-many for the addresses:
Code:
<set name="addresses" lazy="true" cascade="...">
<key column="person_id" />
<one-to-many class="Address" />
</set>
In the Address mapping file we have the normal mapping depending on a foreign/primary key association. In this example it could be:
Code:
<many-to-one name="person"
class="Person"
column="person_id"
cascade="none"
....>
</many-to-one>
Again, it should work other types of bidirectional mappings that support one-to-many.
In the code that is generated (or if you write the code yourself), you'll have a setter and getter for "addresses". You could make these private if you want because you will never be using them outside the class.
Now add to the Person class two "normal" one-to-one setters/getters:
Code:
public Address getAddress()
{
Set addresses = this.getAddresses();
if (addresses== null) return null;
if (addresses.size() == 0) return null;
return (Address)addresses.iterator().next();
}
public void setAddress(Address address)
{
Set addresses = this.getAddresses();
if (addresses == null)
{
addresses = new HashSet();
this.setAddresses(addresses);
}
addresses.clear();
addresses.add(logo);
}
Now you can use your Person class normally and it should act like it supports a lazy one-to-one relationship.
Hope this helps.