Hibernate CRUD operations with example

Read this article to know what is CRUD and how to do CRUD operations in hibernate with example. CRUD stands for Create, Read, Update and Delete. As part of hibernate learning CRUD operations are the most basic operations. In previous examples, I have explained by using the MySQL configuration in Hibernate. But, in the current example, I am explaining by using Oracle as well as MySQL configuration. The choice is yours, use at your convenience.

As of you people already know if we have to change the Database vendors no need to rewrite the entire code, it’s just a configuration file change. So, except the hibernate.cfg.xml file remaining all files logic will be common for both of the databases like Oracle or MySQL.

Before going to write the hibernate logic, we have small work with the databases either Oracle or MySQL. Execute the below query to create the table in the database. Before going to execute the below query make sure you have connected with the specific Schema in the database.

CREATE TABLE USER_HIBERNATE(
USER_ID NUMBER,
FIRST_NAME VARCHAR(20),
LAST_NAME VARCHAR(20),
EMAIL VARCHAR(50),
ORGANIZATION VARCHAR(30));

Here, I have taken a User with the properties of user_id, first_name, last_name, email and organization. Below is the User POJO class with getter and setter methods.

User.java:
package com.jtb.sample;

import java.io.Serializable;

public class User implements Serializable {
 private static final long serialVersionUID = 6143302925040278901L;
 private int user_id;
 private String first_name;
 private String last_name;
 private String email;
 private String organization;

 public int getUser_id() {
  return user_id;
 }

 public void setUser_id(Integer user_id) {
  this.user_id = user_id;
 }

 public String getFirst_name() {
  return first_name;
 }

 public void setFirst_name(String first_name) {
  this.first_name = first_name;
 }

 public String getLast_name() {
  return last_name;
 }

 public void setLast_name(String last_name) {
  this.last_name = last_name;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getOrganization() {
  return organization;
 }

 public void setOrganization(String organization) {
  this.organization = organization;
 }

 public User(int user_id, String first_name, String last_name, String email,
   String organization) {
  super();
  this.user_id = user_id;
  this.first_name = first_name;
  this.last_name = last_name;
  this.email = email;
  this.organization = organization;
 }

 public User() {

 }

}

User.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="com.jtb.sample.User" table="USER_HIBERNATE">
  <id name="user_id" type="int">
   <column name="user_id" />
   <generator class="assigned" />
  </id>
  <property name="first_name" type="string">
   <column name="first_name" length="20" not-null="true" />
  </property>
  <property name="last_name" type="string">
   <column name="last_name" length="20" not-null="false" />
  </property>
  <property name="email" type="string">
   <column name="email" length="50" not-null="true" />
  </property>
  <property name="organization" type="string">
   <column name="organization" length="30" not-null="true" />
  </property>
 </class>
</hibernate-mapping>

This hbm file will contain all the properties which are matching with the java properties as well as Database table columns. <id> tag specifies that is the primary key column of the table. <generator> tag will specify that the primary key column value as manually assigned or system will take care of by declaring the type as increment,…, etc.

HibernateUtil.java:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

 private static final SessionFactory sessionFactory = buildSessionFactory();

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

 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }

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

}

HibernateUtil the file will help us to build and return SessionFactory by using the buildSessionFactory() method from Configuration class.

Hibernate.cfg.xml: 
This file will contain the logic to configure with the databases by reading hibernate properties values. Here, I declare two different logics that will support the Oracle as well as MySQL databases.

For Oracle Database Configuration:
<?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">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@ localhost:1521:XE</property>
  <property name="hibernate.connection.username">jtb</property>
  <property name="hibernate.connection.password">jtb</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">JTB</property>
  <property name="show_sql">true</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <mapping resource="com/jtb/sample/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

For MySQL Database Configuration:
<?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:3306/JTB </property>
          <property name="hibernate.connection.username"> root </property>
          <property name="hibernate.connection.password"> root </property>
          <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>
          <property name="show_sql">true</property>
          <property name="hibernate.hbm2ddl.auto">update</property>

          <mapping resource= "com/jtb/sample/User.hbm.xml"
              package="com.jtb.sample.User" />
     </session-factory>
</hibernate-configuration>

Now, we have to write the logic for CRUD operations. First will see about the Create operation. Create us nothing but Insert. Will you see how to insert a record in a Database table by using hibernate?

CreateUser.java:
import org.hibernate.Session;

import com.jtb.sample.User;
import com.jtb.util.HibernateUtil;

public class CreateUser {

 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();
  
  User user = new User();
  user.setUser_id(123);
  user.setFirst_name("Subbaiah");
  user.setLast_name("Nallamachu");
  user.setEmail("admin@javatbrains.com");
  user.setOrganization("JavaTBrains");
  
  session.save(user);
  session.getTransaction().commit();
 }

}

The above CreateUser.java file contains the logic of inserting the record into the database. By using the save() method from the Session interface will save the record into the database. Until it executes the commit() method which is present in the Transaction interface the changes will not reflect in the database table.

RetrieveUser.java:
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;

import com.jtb.sample.User;
import com.jtb.util.HibernateUtil;

public class RetrieveUser {

 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();
  Criteria ctr = session.createCriteria(User.class);
  List<User> userList = ctr.list();
  if (userList.size() > 0 && userList != null) {
   for (User user : userList) {
    System.out.println("User Id: " + user.getUser_id());
    System.out.println("Name: " + user.getFirst_name() + " "
      + user.getLast_name());
    System.out.println("Email: " + user.getEmail());
    System.out.println("Oraganization: " + user.getOrganization());
    if (userList.size() > 1) {
     System.out.println();
    }
   }
  }
 }
}

To retrieve the information from the database table by using hibernate we have a different set of ways like using Query, Criteria interfaces as well as get and load methods. Query and Criteria interface will use to fetch a bunch of records from a database table and get and load methods are using to fetch specific records from the table. If it doesn’t contain any records from the table it will not execute inside the IF() condition. So, it will not show any information on the console.

UpdateUser.java:
import org.hibernate.Session;

import com.jtb.sample.User;
import com.jtb.util.HibernateUtil;

public class UpdateUser {

 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();
  User user = (User) session.createQuery("from User").list().get(0);
  
  if(user!=null){
   user.setFirst_name("Subba Reddy");
   session.update(user);
   session.getTransaction().commit();
  }
 }
}

The above UpdateUser.java will contains the logic for updating the specific column in a database column. Before going to update the specific column in a record we need to fetch the specific record for that I have used here is HQL query. To update the record into the table I have used the update() method from the Session interface. Until we commit transaction the changes will not reflect into the database table.

DeleteUser.java:

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

import com.jtb.util.HibernateUtil;

public class DeleteUser {

 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();
  String qryStr = "delete USER_HIBERNATE where user_id=?";
  Query query = session.createSQLQuery(qryStr);
  query.setParameter(0, 123);
  int noOfRecords = query.executeUpdate();
  if(noOfRecords>0){
   System.out.println(noOfRecords+" record(s) deleted from table.");
  } 
  session.getTransaction().commit();
 }
}

Finally, we are into the situation to delete the record from the table. To achieve that I have used the normal SQL Query in hibernate.

In this CRUD example, I have covered most of the normal Session methods and HQL queries and normal SQL queries and using Query and Criteria interfaces. 

Comments

Popular posts from this blog

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example