Red Hat Training

A Red Hat training course is available for Red Hat JBoss Web Server

7.6. Other Association Mappings

7.6.1. Complex Association Mappings

More complex association joins are extremely rare. Hibernate handles more complex situations by using SQL fragments embedded in the mapping document. For example, if a table with historical account information data defines accountNumber, effectiveEndDate and effectiveStartDatecolumns, it would be mapped as follows:
<properties name="currentAccountKey">
    <property name="accountNumber" type="string" not-null="true"/>
    <property name="currentAccount" type="boolean">
        <formula>case when effectiveEndDate is null then 1 else 0 end</formula>
<property name="effectiveEndDate" type="date"/>
<property name="effectiveStateDate" type="date" not-null="true"/>
You can then map an association to the current instance, the one with null effectiveEndDate, by using:
<many-to-one name="currentAccountInfo" 
    <column name="accountNumber"/>
In a more complex example, imagine that the association between Employee and Organization is maintained in an Employment table full of historical employment data. An association to the employee's most recent employer, the one with the most recent startDate, could be mapped in the following way:
    <key column="employeeId"/>
        select employeeId, orgId 
        from Employments 
        group by orgId 
        having startDate = max(startDate)
    <many-to-one name="mostRecentEmployer" 
This functionality allows a degree of creativity and flexibility, but it is more practical to handle these kinds of cases using HQL or a criteria query.