Hibernate Application With Annotation Tutorial with Examples

The hibernate application can be created with annotation. There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc.

Hibernate Annotations are based on the JPA 2 specification and supports all the features.

All the JPA annotations are defined in the javax.persistence.* package. Hibernate EntityManager implements the interfaces and life cycle defined by the JPA specification.

The core advantage of using hibernate annotation is that you don't need to create mapping (hbm) file. Here, hibernate annotations are used to provide the meta data.

Example to create the hibernate application with Annotation

Creating Database

Before we start lets create a simple database and table to apply hibernate operations on. Copy and Paste the following sql query in your query editor and execute.
CREATE table STUDENT (ID bigint identity,
rollno varchar(20),
firstname varchar(50),
lastname varchar(50),
course varchar(50),
address varchar(100))


NOTE : Above script is written for SQL Server, you can change accordingly for different DB.

Adding Hibernate Jars

Download latest Hibernate jars from here http://hibernate.org/ and add to your classpath.

Add hibernate.cfg.xml

It is a configuration file, containing informations about the database and mapping file.

put this file under root folder.
<?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">net.sourceforge.jtds.jdbc.Driver</property>
        <property name="hibernate.connection.password">yourdbpassword</property>
        <property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/yourdbname</property>
        <property name="hibernate.connection.username">yourdbusername</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
     <property name="connection.pool_size">1</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.tutorialsdesk.hibernate.bean.Student"/>
        
    </session-factory>
</hibernate-configuration>


Adding Hibernate Utils class

This is a simple java class with a static method, we will use this class to get a session instance of hibernate session factory class.
package com.tutorialsdesk.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; 

 
public class HibernateUtil {
 
 private static final SessionFactory sessionFactory = buildSessionFactory();

  private static SessionFactory buildSessionFactory() {
   try {
    return new AnnotationConfiguration().configure().buildSessionFactory(); 
   } catch (Throwable ex) {
    System.err.println("Initial SessionFactory creation failed." + ex);
    throw new ExceptionInInitializerError(ex);
   }
  }

  public static SessionFactory getSessionFactory() {
   return sessionFactory;
  }

  public static void shutdown() {
   getSessionFactory().close();
  }


}


Adding bean class file

This is a simple pojo consisting of an Student object, we will map this class to relational database using hibernate utilities.

@Entity annotation marks this class as an entity.

@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name bydefault.

@Id annotation marks the identifier for this entity.

@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name bydefault.

package com.tutorialsdesk.hibernate.bean;

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Table;    
@Entity 
@Table(name="STUDENT") 

public class Student {

 @Id    
 @GeneratedValue   
 private int id;
 
 @Column(name="rollno")   
 private String rollno;
 
 @Column(name="firstname")   
 private String firstname;
 
 @Column(name="lastname")     
 private String lastname;
 
 @Column(name="course")   
 private String course;
 
 @Column(name="address")   
 private String address;
 
 public int getId() {
  return id;
 }

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

 public String getRollno() {
  return rollno;
 }

 public void setRollno(String rollno) {
  this.rollno = rollno;
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }

 public String getCourse() {
  return course;
 }

 public void setCourse(String course) {
  this.course = course;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }


 
}


Implementation class code

This is simple java class containing main method to start execution, see the implementation to identify hibernate working in create, retrieve, update and delete operations.
package com.tutorialsdesk.hibernate;

import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
import com.tutorialsdesk.hibernate.bean.Student;

public class AnnotationTest {
public static void main(String[] args) {
 Session session=new AnnotationConfiguration()
         .configure().buildSessionFactory().openSession();
 
 Transaction t=session.beginTransaction();
 AnnotationTest test=new AnnotationTest();
 Student s1=new Student();
 s1.setRollno("2014CS001");
 s1.setFirstname("Ankit");
 s1.setLastname("Yadav");
 s1.setCourse("MCA");
 s1.setAddress("Gomati Nagar, Lucknow");
 
 Student s2=new Student();
 s2.setRollno("2014CS002");
 s2.setFirstname("Rahul");
 s2.setLastname("Verma");
 s2.setCourse("B.Tech");
 s2.setAddress("Niti Khand, Ghaziabad");
 
 test.saveUser(s1);
 test.saveUser(s2);
 
 s2.setCourse("M.Tech");
 test.updateUser(s2);
 
 test.deleteUser(s1);
 
 test.getUser();
 System.out.println("successfully saved");
}
public void saveUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.save(student);

   session.getTransaction().commit();
  }

  public void updateUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.merge(student);

   session.getTransaction().commit();
  }

  public void deleteUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.delete(student);

   session.getTransaction().commit();
  }

  public void getUser() {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   ArrayList<Student> list = (ArrayList<Student>) session.createQuery("from Student").list();
   if (list != null) {
    for (int i = 0; i < list.size(); i++) {
     System.out.println("User ID : " + list.get(i).getId());
     System.out.println("User First Name : "+ list.get(i).getFirstname());
     System.out.println("User Last Name : "+ list.get(i).getLastname());
     System.out.println("User Roll No : " + list.get(i).getRollno());
     System.out.println("User Address : " + list.get(i).getCourse());
    
   }
   }
   session.getTransaction().commit();
  }

}


NEXT READ Example to create web application using hibernate

Hibernate Application With Annotation Tutorial with Examples
Follow us on social media to get latest tutorials, tips and tricks on Hibernate.

Please share us on social media if you like the tutorial.

SHARE
    Blogger Comment
    Facebook Comment