It can also be done quite easily with annotations:
Code:
package com.examscam.mappings;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import org.hibernate.Session;
import com.examscam.HibernateUtil;
@Entity
@IdClass(com.examscam.mappings.CompoundKey.class)
public class Fracture {
Long bankId; Long userId; String bone;
@Id
public Long getBankId() {return bankId;}
@Id
public Long getUserId() {return userId;}
public void setBankId(Long bankId){this.bankId = bankId;}
public void setUserId(Long userId){this.userId = userId;}
public String getBone() {return bone;}
public void setBone(String bone) {this.bone = bone;}
public static void main(String args[]) {
Fracture bone = new Fracture();
bone.setBone("arm");
bone.setBankId( new Long(99));
bone.setUserId(new Long(88));
HibernateUtil.recreateDatabase();
Session session=HibernateUtil.beginTransaction();
session.save(bone);
HibernateUtil.commitTransaction();
}
}
There are other approaches to compound primary key syntax as well. Here's a little Hibernate3 tutorial on the topic of creating compound primary keys for your entities:
http://www.hibernate.org/43.html