Sunday, January 1, 2012

Compound Primary Keys in HIBERNATE

Most of the time we need only 1 primary key. But there are some situations we may need compound primary keys.
Here in hibernate it is simple. We can use 2 classes into 1 table strategy.
import javax.persistence.Entity;
import javax.persistence.Id;

public class Account {

 private AccountCompoundKey compoundKey;
 private int accBalance;
 public AccountCompoundKey getCompoundKey() {
  return compoundKey;
 public void setCompoundKey(AccountCompoundKey compoundKey) {
  this.compoundKey = compoundKey;
 public int getAccBalance() {
  return accBalance;
 public void setAccBalance(int accBalance) {
  this.accBalance = accBalance;

import javax.persistence.Embeddable;

public class AccountCompoundKey implements Serializable{

 private int userId;
 private int accountId;
 public AccountCompoundKey(int userId, int accountId) {
  this.userId = userId;
  this.accountId = accountId;

 public int getUserId() {
  return userId;
 public void setUserId(int userId) {
  this.userId = userId;
 public int getAccountId() {
  return accountId;
 public void setAccountId(int accountId) {
  this.accountId = accountId;
Special Note : As a rule, the class acting as the compound primary key type must implements the Serializable interface.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Test {

  * @param args
 public static void main(String[] args) {
  AnnotationConfiguration config=new AnnotationConfiguration();
  new SchemaExport(config).create(true, true);
  SessionFactory factory=config.buildSessionFactory();
  Session session=factory.getCurrentSession();
  Account acc1=new Account();
  acc1.setCompoundKey(new AccountCompoundKey(1133, 563545));
  Account acc2=new Account();
  acc2.setCompoundKey(new AccountCompoundKey(1136, 986456));;;


Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis