In this section, you will learn how to develop a CRUD application using hibernate annotation.
Follows the following steps for developing the CRUD application in hibernate annotation.
Step 1: Create Domain Entity Class

Student.java

package com.sdnext.hibernate.tutorial.dto;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Table(name="STUDENT")
public class Student implements Serializable 
{

 /**
  * serialVersionUID
  */
 private static final long serialVersionUID = 8633415090390966715L;
 @Id
 @Column(name="ID")
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int id;
 @Column(name="STUDENT_NAME")
 private String studentName;
 @Column(name="ROLL_NUMBER")
 private int rollNumber;
 @Column(name="COURSE")
 private String course;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
 public int getRollNumber() {
  return rollNumber;
 }
 public void setRollNumber(int rollNumber) {
  this.rollNumber = rollNumber;
 }
 public String getCourse() {
  return course;
 }
 public void setCourse(String course) {
  this.course = course;
 }
}

 

Step 2: Create Hibernate Configuration file 
hibernate.cfg.xml
file contains
(a.) database connection setting (database driver (com.mysql.jdbc.Driver), url (jdbc:mysql://localhost:3306/hibernateDB2), username (root) and password (root)),
(b.) SQL dialect (dialect – org.hibernate.dialect.MySQLDialect),
(c.) enable hibernate’s automatic session context management (current_session_context_class – thread),
(d.) disable the second level cache (cache.provider_class – org.hibernate.cache.NoCacheProvider),
(e.) print all executed SQL to stdout (show_sql – true) and
(f.) drop and re-create the database schema on startup (hbm2ddl.auto – none).

<hibernate-configuration> 
 <session-factory> 
  <!-- Database connection settings -->
   <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
   <property name="connection.url">jdbc:mysql://localhost:3306/hibernateDB2</property> 
   <property name="connection.username">root</property> 
   <property name="connection.password">root</property> 

  <!-- JDBC connection pool (use the built-in) -->
   <property name="connection.pool_size">1</property> 

  <!-- SQL dialect -->
   <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 

  <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property> 
  
  <!-- Disable the second-level cache -->
   <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 

  <!-- Echo all executed SQL to stdout -->
   <property name="show_sql">true</property> 
  
  <!-- Drop and re-create the database schema on startup -->
   <property name="hbm2ddl.auto">update</property> 
    
   <mapping class="com.sdnext.hibernate.tutorial.dto.Student">
      
  </mapping></session-factory> 
 </hibernate-configuration>

Step 3: Create Hibernate Utility Class
HibernateUtil.java

package com.sdnext.hibernate.tutorial.utility;

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

public class HibernateUtil 
{
 private static final SessionFactory sessionFactory;
 static
 {
  try
  {
   sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
  }
  catch(Throwable th){
   System.err.println("Enitial SessionFactory creation failed"+th);
   throw new ExceptionInInitializerError(th);
  }
   }
   public static SessionFactory getSessionFactory(){
    return sessionFactory;
   }
}

Step 4: Create Student on the database.
CreateStudent.java

package com.sdnext.hibernate.tutorial;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;

public class CreateStudent {

 /**
  * @param args
  */
 public static void main(String[] args) 
 {
  //Create student entity object
  Student student = new Student();
  student.setStudentName("Dinesh Rajput");
  student.setRollNumber(01);
  student.setCourse("MCA");
  
  //Create session factory object
  SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  //getting session object from session factory
  Session session = sessionFactory.openSession();
  //getting transaction object from session object
  session.beginTransaction();
  
  session.save(student);
  System.out.println("Inserted Successfully");
  session.getTransaction().commit();
  session.close();
  sessionFactory.close();
 }
}
OUTPUT:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into STUDENT (COURSE, ROLL_NUMBER, STUDENT_NAME) values (?, ?, ?)
Inserted Successfully

 

CRUD Operations Using Hibernate

Now the following code the reading the student data from database.
Step 5: Reading the Student data from the database table STUDENT
ReadStudent.java

package com.sdnext.hibernate.tutorial;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;

public class ReadStudent {

 /**
  * @param args
  */
 public static void main(String[] args) 
 {
  //Create session factory object
  SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  //getting session object from session factory
  Session session = sessionFactory.openSession();
  //getting transaction object from session object
  session.beginTransaction();
  Query query = session.createQuery("from Student");
  List students = query.list();
  for(Student student : students)
  {
System.out.println("Roll Number: "+student.getRollNumber()+", Student Name: "+student.getStudentName()+", Course: "+student.getCourse());
  }
  session.getTransaction().commit();
  sessionFactory.close();
 }
}
Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_, student0_.COURSE as COURSE0_, student0_.ROLL_NUMBER as ROLL3_0_, student0_.STUDENT_NAME as STUDENT4_0_ from STUDENT student0_
Roll Number: 1, Student Name: Dinesh Rajput, Course: MCA
Roll Number: 2, Student Name: Anamika Rajput, Course: PGDCP
Roll Number: 3, Student Name: Adesh Rajput, Course: MA
Roll Number: 4, Student Name: Vinesh Rajput, Course: BA

CRUD Operations in Hibernate

 

The following code is for updating the data into the database table “STUDENT”.
Step 6: Update the Student Record in the Database.
UpdateStudent.java

package com.sdnext.hibernate.tutorial;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;

public class UpdateStudent {

 /**
  * @param args
  */
 public static void main(String[] args) 
 {
  //Create session factory object
  SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  //getting session object from session factory
  Session session = sessionFactory.openSession();
  //getting transaction object from session object
  session.beginTransaction();
  
  Student student = (Student)session.get(Student.class, 2);
  student.setStudentName("Sweety Rajput");
  System.out.println("Updated Successfully");
  session.getTransaction().commit();
  sessionFactory.close();
 }
}
Output:

 

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_0_, student0_.COURSE as COURSE0_0_, student0_.ROLL_NUMBER as ROLL3_0_0_, student0_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT student0_ where student0_.ID=?
Hibernate: update STUDENT set COURSE=?, ROLL_NUMBER=?, STUDENT_NAME=? where ID=?
Updated Successfully
Annotation and Configuration

Step 7: Delete the student data from the database.
DeleteStudent.java

package com.sdnext.hibernate.tutorial;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.sdnext.hibernate.tutorial.dto.Student;
import com.sdnext.hibernate.tutorial.utility.HibernateUtil;

public class DeleteStudent {

 /**
  * @param args
  */
 public static void main(String[] args) 
 {
  //Create session factory object
  SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  //getting session object from session factory
  Session session = sessionFactory.openSession();
  //getting transaction object from session object
  session.beginTransaction();
  Student student = (Student)session.load(Student.class, 4);
  session.delete(student);
  System.out.println("Deleted Successfully");
  session.getTransaction().commit();
     sessionFactory.close();
 }
}
Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_0_, student0_.COURSE as COURSE0_0_, student0_.ROLL_NUMBER as ROLL3_0_0_, student0_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT student0_ where student0_.ID=?
Deleted Successfully
Hibernate: delete from STUDENT where ID=?

delete
CRUD

 

How to solve QuerySyntaxException (table is not mapped) in hibetnate?

In the Next Chapter we will discuss about the Object states in the Hibernate.

      <<Previous Chapter 22<<    >>Next Chapter 24>>