Hibernate Annotations Tutorial

Hibernate Annotations Tutorial explains step by step details of setting / configuring Hibernate with Eclipse

Hibernate is popular open source ORM (Object Relation Mapping) tool for Java platform, for mapping an entity to a traditional relational database like Oracle, MySQL etc

By using Hibernate, we can done database operations like Create, Read, Update & Delete etc, with very little code.

We can also use Hibernate Query Language (HQL) for the jdbc operation, if you are using HQL, then you can follow this example of Hibernate Query Tutorial

You can also view  Hibernate Tutorial

Note

You can also check following related Hibernate Tutorial Series

1)    Hibernate One To One Relation Mapping Example
2)    Hibernate One To Many Relation Mapping Example
3)    Hibernate Many To One Relation Mapping Example
4)    Hibernate Many To Many Relation Mapping Example
Required Libraries

You need to download

  1. JDK 6
  2. Eclipse 3.7
  3. Hibernate 3.6.8

Following jar must be in classpath

  1. antlr-2.7.6.jar
  2. commons-collections-3.1.jar
  3. javassist-3.12.0.GA.jar
  4. jta-1.1.jar
  5. hibernate-jpa-2.0-api-1.0.1.Final.jar
  6. hibernate3.jar
  7. mysql-connector-java-5.1.18-bin.jar
  8. dom4j-1.6.1.jar
  9. slf4j-api-1.6.1.jar

Hibernate Annotation Required Libraries

Starting with version 3.5, Annotations and EntityManager have been merged back into the Hibernate Core code base as individual modules so following jar's are not needed,

hibernate-commons-annotations.jar
ejb3-persistence.jar
hibernate-annotations.jar

I am creating a sample project that persists Student object (simple POJO (Plain Old Java Object)) into database using hibernate.

Firstly create a Java Project (File->New->Project), select Java Project and click next, provide name as "HibernateExample" according to following screenshot

Create Hibernate Project Hibernate Tutorial

hibernate.cfg.xml

<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.javatips.student.Student"/>
    </session-factory>
</hibernate-configuration>

HibernateUtil.java

HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. Its implementation is shown bellow:

package com.javatips.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 
private static final SessionFactory sessionFactory;
 
static {
   
try {
     
sessionFactory = new Configuration().configure().buildSessionFactory();
   
} catch (Throwable ex) {
     
System.err.println("Initial SessionFactory creation failed." + ex);
     
throw new ExceptionInInitializerError(ex);
   
}
  }

 
public static SessionFactory getSessionFactory() {
   
return sessionFactory;
 
}
}

Create a Student Object(Student.java)

package com.javatips.student;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
(name="StudentDetails")
public class Student implements java.io.Serializable {

 
private long studentId;
 
private String studentName;

 
public void setStudentId(long studentId) {
   
this.studentId = studentId;
 
}
 
@Id
  @GeneratedValue
  @Column
(name="STUDENT_ID")
 
public long getStudentId() {
   
return studentId;
 
}

 
public void setStudentName(String studentName) {
   
this.studentName = studentName;
 
}
 
@Column(name="STUDENT_NAME", nullable=false)
 
public String getStudentName() {
   
return studentName;
 
}

}
@Entity declares the class as an entity (i.e. a persistent POJO class)
@Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity mapping. If no @Table is defined the default values are used: the unqualified class name of the entity.
@Id declares the identifier property of this entity.
@GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
@Column annotation is used to specify the details of the column to which a field or property will be mapped. If the @Column annotation is not specified by default the property name will be used as the column name.

Package Structure

Hibernate Annotation Package Structure

Testing (HibernateExample.java)

package com.javatips.student;

import java.util.List;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.javatips.util.HibernateUtil;

public class HibernateExample {

 
public static void main(String[] args) {
   
HibernateExample example = new HibernateExample();
    Long studentId2 = example.saveStudent
("Sumith");
    Long studentId3 = example.saveStudent
("Anoop");
    example.listStudent
();
    example.updateStudent
(studentId3, "Rockey");
    example.deleteStudent
(studentId2);
    example.listStudent
();

 
}

 
public Long saveStudent(String studentName) {
   
Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction =
null;
    Long studentId =
null;
   
try {
     
transaction = session.beginTransaction();
      Student student =
new Student();
      student.setStudentName
(studentName);
      studentId =
(Long) session.save(student);
      transaction.commit
();
   
} catch (HibernateException e) {
     
transaction.rollback();
      e.printStackTrace
();
   
} finally {
     
session.close();
   
}
   
return studentId;
 
}

 
public void listStudent() {
   
Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction =
null;
   
try {
     
transaction = session.beginTransaction();
     
@SuppressWarnings("unchecked")
     
List<Student> Students = session.createQuery("from Student").list();
     
for (Iterator<Student> iterator = Students.iterator(); iterator.hasNext();) {
       
Student student = (Student) iterator.next();
        System.out.println
(student.getStudentName());
     
}
     
transaction.commit();
   
} catch (HibernateException e) {
     
transaction.rollback();
      e.printStackTrace
();
   
} finally {
     
session.close();
   
}
  }

 
public void updateStudent(Long studentId, String studentName) {
   
Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction =
null;
   
try {
     
transaction = session.beginTransaction();
      Student student =
(Student) session.get(Student.class, studentId);
      student.setStudentName
(studentName);
      transaction.commit
();
   
} catch (HibernateException e) {
     
transaction.rollback();
      e.printStackTrace
();
   
} finally {
     
session.close();
   
}
  }

 
public void deleteStudent(Long studentId) {
   
Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction =
null;
   
try {
     
transaction = session.beginTransaction();
      Student student =
(Student) session.get(Student.class, studentId);
      session.delete
(student);
      transaction.commit
();
   
} catch (HibernateException e) {
     
transaction.rollback();
      e.printStackTrace
();
   
} finally {
     
session.close();
   
}
  }
}

Output

Hibernate: insert into StudentDetails (STUDENT_NAME) values (?)
Hibernate: insert into StudentDetails (STUDENT_NAME) values (?)
Hibernate: select student0_.STUDENT_ID as STUDENT1_0_, student0_.STUDENT_NAME as STUDENT2_0_ from StudentDetails student0_
Sumith
Anoop
Hibernate: select student0_.STUDENT_ID as STUDENT1_0_0_, student0_.STUDENT_NAME as STUDENT2_0_0_ from StudentDetails student0_ where student0_.STUDENT_ID=?
Hibernate: update StudentDetails set STUDENT_NAME=? where STUDENT_ID=?
Hibernate: select student0_.STUDENT_ID as STUDENT1_0_0_, student0_.STUDENT_NAME as STUDENT2_0_0_ from StudentDetails student0_ where student0_.STUDENT_ID=?
Hibernate: delete from StudentDetails where STUDENT_ID=?
Hibernate: select student0_.STUDENT_ID as STUDENT1_0_, student0_.STUDENT_NAME as STUDENT2_0_ from StudentDetails student0_
Rockey

 









Your email address will not be published. Required fields are marked *