1.Annotation
Husband class: @JoinColumns ({@JoinColumn(name="",referencedColumnName="") , @JoinColumn(name="",referencedColumnName="")})
@Entity
public class Husband { private int id; private String name; private Wife wife; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @OneToOne //name of the column; By default is (wife_id) @JoinColumns( { @JoinColumn(name="wifeId",referencedColumnName="id"),
@JoinColumn(name="wifeName",referencedColumnName="name") } ) public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity @IdClass(value=WifePK.class) public class Wife { private int id; private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } @Id public String getName() { return name; } public void setName(String name) { this.name = name; } } public class WifePK implements java.io.Serializable{ private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean equal(Object o){ if(o instanceof WifePK){ WifePK p=(WifePK)o; if(this.name.equals(p.getName())&&this.id==p.getId()){ return true; } } return false; } public int hashCode(){ return this.name.hashCode(); } }
2.XML
Student class: under <many-to-one name="xx"> tag, we should name each column of composite primary key of xx as <column name="xx">
<hibernate-mapping package="com.hibernate.model">
<class name="Student">
<id name="id"></id>
<property name="name"></property>
<property name="age"></property>
<property name="classID"></property>
<many-to-one name="stuIdCard" >
<column name ="id_fk"/>
<column name ="name_fk"/>
</many-to-one>
</class>
<class name="com.hibernate.model.StuIdCard">
<composite-id name="pk" class="com.hibernate.model.StudentPK">
<key-property name="id"></key-property>
<key-property name="name"></key-property>
</composite-id>
<property name="num"></property>
</class>