Home  >  Hibernate

Example of @NaturalId in Hibernate Annotation

By Arvind Rai, February 01, 2013
@NaturalId is an Identifier in Hibernate Annotation. @NaturalId provides unique constraints to database schema. The scenario to use @NaturalId is when we want to generate identifier any natural key. Like Pan number, voter id etc. These are natural keys that are generally unique. In Hibernate Annotation we can use that in Criteria query.
Car.java
package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
@Entity
@Table(name="car")  
public class Car implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue
	private int id;
	@NaturalId
	private String vehicleRegNum; 	
	@Column(name="name")
	private String name;
	public Car(String vehicleRegNum,String name){
    	        this.vehicleRegNum=vehicleRegNum;
    	        this.name=name;
        }
	public String getVehicleRegNum() {
		return vehicleRegNum;
	}
	public void setVehicleRegNum(String vehicleRegNum) {
		this.vehicleRegNum = vehicleRegNum;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
} 
hibernate.cfg.xml
<!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.connection.url">
    jdbc:mysql://localhost:3306/hibernate</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="com.concretepage.persistence.Car"/>
   </session-factory>
</hibernate-configuration>
 
HibernateUtil.java
package com.concretepage.util;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Restrictions;
import com.concretepage.persistence.Car;
public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
	    static {
	        try {
	            concreteSessionFactory = new AnnotationConfiguration()
	                    .configure().buildSessionFactory();
	        } catch (Throwable ex) {
	            throw new ExceptionInInitializerError(ex);
	        }
	    }
	    public static Session getSession()
	            throws HibernateException {
	        return concreteSessionFactory.openSession();
	    }
	    public static void main(String... args){
	    	Session session=getSession();
	    	session.beginTransaction();
	    	Car c1= new Car("UP65 BN 2343 ","Maruti");
	    	session.persist(c1);
	    	Car c2= new Car("DL60 AN 7845 ","Tata");
	    	session.persist(c2);
	    	session.getTransaction().commit();
	    	List<Car> list=session.createCriteria(Car.class).add(Restrictions.naturalId().set("vehicleRegNum","UP65 BN 2343")).list();
	    	for(Car c:list){
	    		System.out.println(c.getName());
	    	}
	    	session.close();
	    }
	} 
Output
Hibernate: insert into car (name, vehicleRegNum) values (?, ?)
Hibernate: insert into car (name, vehicleRegNum) values (?, ?)
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.vehicleRegNum as vehicleR3_0_0_ from car this_ where (this_.vehicleRegNum=?)
Maruti 
Data will be inserted in database as
Example of @NaturalId in Hibernate Annotation
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us