Hibernate Annotation Example

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

Hibernate Annotation Example

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