I rarely generated mapping and pojo files using the respective tools available.
But generating an ID class for composite key makes sense and I always have classes implemented in this way. And if you observe the ID class would implement Serializable interface as this is requirement for any ID class which contains elements for composite key.
For example, with the below example mapping file, the classes are given further down.
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="learn.hibernate">
<class name="MyComposite" table="My_Composite_Table">
<composite-id name="myCompositeId" class="MyCompositeId">
<key-property name="propertyA" column="prop_a"/>
<key-property name="propertyB" column="prop_a"/>
<key-property name="propertyC" column="prop_a"/>
<composite-id>
<property name="propertyD" column="prop_d"/>
</class>
</hibernate-mapping>
Code:
public class MpComposite {
private MyCompositeId myCompositeId;
private String propertyD;
// getters and setters
}
public class MyCompositeId implements Serializable {
private String propertyA;
private String propertyB;
private String propertyC;
//getters and setters for above properties...
}
The second approach, I sometimes follow, is to have one class extend other class with composite key fields.
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="learn.hibernate">
<class name="MyComposite" table="My_Composite_Table">
<composite-id>
<key-property name="propertyA" column="prop_a"/>
<key-property name="propertyB" column="prop_a"/>
<key-property name="propertyC" column="prop_a"/>
<composite-id>
<property name="propertyD" column="prop_d"/>
</class>
</hibernate-mapping>
Code:
public class MpComposite extends MyCompositeId {
private String propertyD;
// getters and setters
}
public class MyCompositeId implements Serializable {
private String propertyA;
private String propertyB;
private String propertyC;
//getters and setters for above properties...
}