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.
Account.java
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Account {

 private AccountCompoundKey compoundKey;
 private int accBalance;
 
 @Id
 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;
 } 
}

AccountCompoundKey.java
import java.io.Serializable;

import javax.persistence.Embeddable;

@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.
Test.java
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();
  config.addAnnotatedClass(Account.class);
  config.configure("hibernate.cfg.xml");
  
  new SchemaExport(config).create(true, true);
  
  SessionFactory factory=config.buildSessionFactory();
  Session session=factory.getCurrentSession();
  
  session.beginTransaction();
  
  Account acc1=new Account();
  acc1.setAccBalance(25000);
  acc1.setCompoundKey(new AccountCompoundKey(1133, 563545));
  
  Account acc2=new Account();
  acc2.setAccBalance(32000);
  acc2.setCompoundKey(new AccountCompoundKey(1136, 986456));
  
  session.save(acc1);
  session.save(acc2);
  
  session.getTransaction().commit();
 }
}
Result

0 comments:

Post a Comment

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