There really is no mystery when it comes to creating compoung primary keys with Hibernate. There are a few compound primary key strategies, the simplest is to just create an @Embeddable class with your keys defined:
Code:
package com.examscam.mappings;
import javax.persistence.Embeddable;
/* First Iteration of the CompoundKey Class */
@Embeddable
public class CompoundKey implements
java.io.Serializable{
private Long userId;
private Long bankId;
public CompoundKey() {}
public CompoundKey(Long user, Long bank) {
userId = user;
bankId = bank;
}
public Long getBankId() {return bankId;}
public void setBankId(Long bankId) {
this.bankId = bankId;
}
public Long getUserId() {return userId;}
public void setUserId(Long userId) {
this.userId = userId;
}
}
This example comes from this free tutorial:
http://www.hiberbook.com/HiberBookWeb/learn.jsp?tutorial=15usingcompoundprimarykeysThen, just reference the @Embeddable class in your entity class. Here's the Interest class that uses the compound primary key. (Get it? Compound Interest???) :)
Code:
package com.examscam.mappings;
import javax.persistence.*; import org.hibernate.Session;
import com.examscam.HibernateUtil;
@Entity
public class Interest {
private CompoundKey id;
private double rate;
@Id
public CompoundKey getId() {return id;}
public void setId(CompoundKey id) {this.id=id;}
public double getRate() {return rate;}
public void setRate(double rate) {this.rate=rate;}
public static void main(String args[]) {
Interest rate = new Interest();
rate.setRate(18.5);
Long wayne=new Long(99); Long mario=new Long(88);
CompoundKey key = new CompoundKey(wayne, mario);
rate.setId(key);
HibernateUtil.recreateDatabase();
Session session = HibernateUtil.beginTransaction();
session.save(rate);
HibernateUtil.commitTransaction();
}
}
Then, you just code like normal:
Code:
public static void main(String args[]) {
Interest rate = new Interest();
rate.setRate(18.5);
Long wayne=new Long(99); Long mario=new Long(88);
CompoundKey key = new CompoundKey(wayne, mario);
rate.setId(key);
HibernateUtil.recreateDatabase();
Session session = HibernateUtil.beginTransaction();
session.save(rate);
HibernateUtil.commitTransaction();
}
There are other strategies, like the @IdClass and @EmbeddableId as well, that you can look at. Here's a full tutorial on Hibernate Compound Primary Keys and full Hibernate3 example code:
http://www.hiberbook.com/HiberBookWeb/learn.jsp?tutorial=15usingcompoundprimarykeys[/code]