Hibernate Annotation Example

Hibernate annotation example explains you how to create an application to show data of a table using Hibernate.



Hibernate Examples Hibernate 5 build SessionFactory Example Hibernate 5 SessionFactory Example Hibernate 5 Annotation Example How to download Hibernate 5.x? Hibernate 5 Features Hibernate 5 Tutorials Learning Hibernate ORM - Free Training/Tutorial videos of Hibernate ORM with Java How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate ORM 4.2.21.Final Released - Create CURD application in latest Hibernate Hibernate ORM 4.2.21 Tutorial - Learn Hibernate ORM Framework Hibernate Error: Failed to create sessionFactory object.java.lang.NoClassDefFoundError How to create Hibernate Project in Eclipse? Examples of Hibernate Criteria Query Hibernate ORM 4.3.6.Final released Hibernate ORM 4.2.14.Final released Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate association and join example Learn Hibernate programming with Examples Introduction to Hibernate Framework Hibernate Tutorial: Learn Hibernate with examples Hibernate 4.3 Hello World: Example Hibernate ORM 4.3.1.Final released How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate ORM 4.3.0.Final released Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial

Hibernate Annotation Example

In this section we will read about how to create a hibernate application using annotation. Here we will see an example of retrieving data from database table.

To create an application in Hibernate using annotation we will use the annotation classes instead of creating an additional hibernate mapping XML file. In this example we will use the Eclipse IDE for writing, compiling and executing the code and MySQL for querying to database. In this example we will use the following annotations which belongs to the javax.persistence package.

  • @Entity : Specifies the class as an Entity bean.
  • @Table : This annotation is used to map the class name with the table name. If this annotation is not used by default Hibernate uses the class name as a table name.
  • @Id : Specified the Entity bean Identifier property.
  • @GeneratedValue : Specified the primary key generation strategy if not used then by default AUTO strategy is used.
  • @Column : This annotation is used to map the field or property name with the table's column name.


Here an example is being given which will demonstrate you about how to create a hibernate application using annotation. In this example I will create a POJO class that contains some data members and their setter/getter methods and constructors. These setter/getter methods are used to set/get the value of data members and constructors are to use to initialize the value. Then I will create a class for creating and getting the SessionFactory. Then I will create a class where I will get the SessionFactory object and create a session from the session factory object and then begin the transaction using a session object then I have used the createQuery() method of Session to retrieve the data from table. Then I have displayed all the records of a table.

First of all we will have to create a database table. So, I have created a table named 'student'

CREATE TABLE `student` (                
           `rollno` varchar(15) NOT NULL,        
           `name` varchar(20) DEFAULT NULL,      
           `class` varchar(5) DEFAULT NULL,      
           `section` varchar(5) DEFAULT NULL,    
           PRIMARY KEY (`rollno`)                
         ) ENGINE=InnoDB DEFAULT CHARSET=latin1

I have inserted some bulk records into the table using SQL insert query. Then the table will be displayed as follows :

To create an application in Hibernate you should have installed the following in your system :

  • JDK 5 or higher version
  • Eclipse IDE
  • MySQL
  • Hibernate Jar files and Hibernate annotation supported Jar files

Required JAR files

JAR files required for this example are as follows :

  • antlr-2.7.7.jar
  • classmate-0.5.4.jar
  • commons-collections-3.2.1.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.0.0.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • jandex-1.0.3.Final.jar
  • javassist-3.12.1.GA.jar
  • jboss-logging-3.1.0.CR2.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.3-rc-bin.jar

Directory Structure


package net.roseindia.pojo;

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

public class StudentPojo {

	private int rollno;
	private String name;
	private String classs;
	private String section;

	public StudentPojo() {

	public StudentPojo(int rollno, String name, String classs, String section) {
		this.rollno = rollno;
		this.name = name;
		this.classs = classs;
		this.section = section;

	public int getRollno() {
		return rollno;

	public void setRollno(int rollno) {
		this.rollno = rollno;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public String getClasss() {
		return classs;

	public void setClasss(String classs) {
		this.classs = classs;

	public String getSection() {
		return section;

	public void setSection(String section) {
		this.section = section;


package net.roseindia.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class StudentFactory {

	private static ServiceRegistry serviceRegistry;
	private static final SessionFactory sessionFactory;
	static {
	try {
	Configuration configuration = new Configuration();
	serviceRegistry = new ServiceRegistryBuilder().applySettings(
	sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	} catch (Throwable ex) {
	System.err.println("Failed to create sessionFactory object." + ex);
	throw new ExceptionInInitializerError(ex);
	public static SessionFactory getSessionFactory() {
		return sessionFactory;



package net.roseindia.core;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import net.roseindia.pojo.*;
import net.roseindia.util.*;
public class StudentDetail
private static SessionFactory sessionFactory = null;
public static void main(String[] args)
Session session = null;
StudentFactory factory = new StudentFactory();
sessionFactory = factory.getSessionFactory();
session = sessionFactory.openSession(); 
System.out.println("Fetching Record.....");
Transaction tx = session.beginTransaction();
Query queryResult = session.createQuery("from StudentPojo"); 
java.util.List allUsers; 
allUsers = queryResult.list();
System.out.println("Roll No Name Class Section");
for (int i = 0; i < allUsers.size(); i++) { 
StudentPojo sb = (StudentPojo) allUsers.get(i);
System.out.println(sb.getRollno()+" \t "+sb.getName()+"\t "+
sb.getClasss()+"\t "+sb.getSection());
catch (Exception e)


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/record
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</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.current_session_context_class">thread</property>

<mapping class="net.roseindia.pojo.StudentPojo" />


When you will compile and execute the StudentDetail.java file then the output will be as follows :

Download Source Code


Share on Google+Share on Google+

Hibernate Annotation Example

Posted on: August 9, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Hibernate Annotation Example  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image