I have an application where some of the tables have 5 element composit-ids, some have 3 element, and some have 2. Our DBAs mandate that a primary key may not be a surrogate and must describe the data (sequence numbers are not allowed, if it is at all possible).
Hibernate is really easy with this. Instead of a long winded paragraph, here is some code.
Primary key example:
Code:
public class FinNumRteNumPK implements Serializable {
private String financeNumber = "";
private String routeNumber = "";
public FinNumRteNumPK() {
super();
}
// getter and setters
hibernate mapped example
Code:
public class TestVO implements Serializable {
private FinNumRteNumPK primarykey = null;
private String something = "";
public TestVO () {
super();
primarykey = new FinNumRteNumPK ();
}
}
//getter and setters
Hibernate mapping
Code:
<hibernate-mapping>
<class name="TestVO "
table="MY_TABLE">
<composite-id
name="primarykey"
class="FinNumRteNumPK " >
<key-property
name="financeNumber"
type="string"
column="FIN_NBR"
/>
<key-property
name="routeNumber"
type="string"
column="RTE_NBR"
/>
</composite-id>
<property name="something "
type="string"
update="true"
insert="true"
access="property"
column="SOMETHING"
lazy="false"
>
</property>
If I wanted to search based on this primary key
Code:
StringBuffer sb = new StringBuffer("from TestVo p where p.primarykey.routeNumber = :route ");
sb.append("and p.primarykey.financeNumber = :finance ");
Query query = session.createQuery(sb.toString());
query.setString("finance", finance);
query.setString("route", route);
query.list();
That's it. To recap, I have my primary key java class, my value object class, my hibernate mapping for that value object.