Saturday, February 22, 2014

How to Map Composite Primary Key using annotations in Hibernate ?

What is Composite primary key ?

Sometimes you may not have primary key for table.In such cases you use combination of properties
to uniquely identify a record in the table.The combination of fields is called composite primary key.

Normally in hibernate you map primary key with @Id.

To map composite primary key you have to define a new class with the properties that
uniquely identify a record.This class should implement Serializable.

This class need to be annotated with @Embeddable annotation.

Example:

CustomerId.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package hibex;

import java.io.Serializable;
import javax.persistence.Embeddable;

/**
 *
 * @author Rishitha
 */
@Embeddable
public class CustomerId implements Serializable{
  private String cfname;
  private String clname;
  public CustomerId(){}
  public CustomerId(String cfname, String clname) {
    this.cfname = cfname;
    this.clname = clname;
  }

    public String getCfname() {
        return cfname;
    }

    @Override
    public boolean equals(Object obj) {
        CustomerId cp =(CustomerId)obj;
        if(this.cfname.equals(cp.getCfname()) && this.clname.equals(cp.getClname())){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.cfname.hashCode()+this.clname.hashCode();
    }

    public void setCfname(String cfname) {
        this.cfname = cfname;
    }

    public String getClname() {
        return clname;
    }

    public void setClname(String clname) {
        this.clname = clname;
    }
 
 
}

Customer.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package hibex;

import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;

/**
 *
 * @author Rishitha
 */
@Entity
public class Customer {
 @Id
  private CustomerId id;

  private String email;

   
  public CustomerId getId() {
        return id;
    }

    public void setId(CustomerId id) {
        this.id = id;
    }

  
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
 
  public Customer(){}
 
 
 
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package hibex;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.jl.vo.StudentTo;

/**
 *
 * @author Rishitha
 */
public class CustomerCompTest {
    public static void main(String args[]){
       
         SessionFactory sf = new Configuration().configure("hibernate.cfgComp.xml").buildSessionFactory();
       
     
        Session ses = sf.openSession();
      
        Transaction tx = null;
        try{
            tx = ses.beginTransaction();
            CustomerId cid = new CustomerId("Anil","Chintha");
           
            Customer c =(Customer)ses.get(Customer.class, cid);
          
            if(c!= null)
                System.out.println("Email of customer is "+c.getEmail());
           
            //Save new student
            CustomerId scid = new CustomerId("Prasanna","Chintha");
            Customer sc = new Customer();
            sc.setId(scid);
            sc.setEmail("sunil@gmail.com");
            ses.save(sc);
            tx.commit();
        }catch(Exception e ){
            e.printStackTrace();
        }
       
  }
}



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto" >update</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="hibex.Customer"/>
   
   
  </session-factory>
</hibernate-configuration>







No comments:

Post a Comment