Problem
You want to create association based on some advanced condition not just primary and foreign keys.
For example each Asset can have one or more AssetOwners but only one of them is the primary owner.
Solution
AssetOwner.hbm.xml
<class name="AssetOwner" table="asset_owner"> <id name="id" column="owner_id"> ... </class>
Asset.hbm.xml
<class name="Asset" table="asset"> <id name="id" column="asset_id"> ... <join table="asset_owner" inverse="true"> <subselect> SELECT o.owner_id AS primary_owner, o.asset_id FROM asset_owner o WHERE o.asset_id = asset_id AND o.is_primary = true </subselect> <key column="asset_id"/> <many-to-one name="primaryOwner" column="primary_owner" class="AssetOwner"/> </join> </class>
Select contains two columns:
- asset_id which is used to filter out only these AssetOwners who own given Asset
- primary_owner which is used to map only the AssetOwner who is the primary owner
Second important thing is that you must use inverse=true to make sure that Hibernate will not try to persist primaryOwner field when Asset is saved.