On first look, this simply looks like a question about compound primary keys, right? Composite primary keys are no mystery in Hibernate, and there are a few ways to implement them, includinging IdClass and EmbeddedId. Personally, I just use the Embeddable annotation if I can.
Hibernate3 Tutorial on Using Composite Primary Keys: Mapping Compound Id Keys
So, with a compound key like this:
You create an embeddable object, as so:
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;
}
}
Hibernate3 Tutorial on Using Composite Primary Keys: Mapping Compound Id KeysThen you just use it in your class:
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();
}
}
Here's the full tutorial and sample Java code from my site:
Hibernate3 Tutorial on Using Composite Primary Keys: Mapping Compound Id Keys
It's just that easy!