Skip to main content

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

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...