CRUD operations in Hibernate using annotations

Create a Java Program to perform CRUD operations in hibernate using annotations. In this Hibernate tutorial, let’s create a simple Java Maven project to create a connection with the database and perform Create, Read, Update and Delete(CRUD) operation using Hibernate.

CRUD operations in Hibernate

Before performing crud operations in hibernate. we need some configuration in our java application. below are the required steps for Hibernate configuration.

ADD Maven dependencies for Hibernate

As we are using the maven project, We need to add hibernation dependencies or Jar to enable hibernate capabilities in our java application, so add the below dependencies in the pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com</groupId>
 <artifactId>CbHibEample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>CbHibEample</name>
 <url>http://maven.apache.org</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>

 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.0.1.Final</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>4.2.0.Final</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate.common</groupId>
   <artifactId>hibernate-commons-annotations</artifactId>
   <version>4.0.1.Final</version>
   <classifier>tests</classifier>
  </dependency>
  <dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.0-api</artifactId>
   <version>1.0.1.Final</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.0.1.Final</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.27</version>
  </dependency>

 </dependencies>
</project>

Hibernate configuration(hibernate.cfg.xml)

Create an XML file and keep this file in the src folder also the name “hibernate.cfg.xml”. Name is not important to be the same but yes to In terms of development standards, will recommend keeping the same name.

  • Database connection setting (database driver (com.mysql.jdbc.Driver), url (jdbc:mysql://localhost:3306/hibernate_tutorial), username (root) and password (root)).
  • <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>Enable Mysql Database.
  • Enable hibernate’s automatic session context management (current_session_context_class – thread),
  • Disable the second level cache (cache.provider_class – org.hibernate.cache.NoCacheProvider),
  • Print all executed SQL to stdout (show_sql – true) and
  • Drop and re-create the database schema on startup (hbm2ddl.auto – none).
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
 
  <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_tutorial</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="hibernate.show_sql">true</property>
        <property name="hibernate.current_session_context_class">thread</property>
  
 </session-factory>
</hibernate-configuration>

Create Entity Class using hibernate annotations

Entity classes is a simple Java class where we will use some annotation that makes it entity class to map with a database table.

@Entity annotation is used to make the classes an entity.

@Table annotation is used to map the class with the database table name like @Table(name = “users”)

@Column annotation is used to map the column name with fields like @Column(name = “id”)

Users.java

package com.loginexample.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class Users {

 @Id
 @Column(name = "id")
 private long id;
 
 @Column(name = "username")
 private String username;
 
 @Column(name = "password")
 private String password;
 
 @Column(name = "firstName")
 private String firstName;
 
 @Column(name = "lastName")
 private String lastName;
 

 public Users(String username, String password, String firstName, String lastName) {
  
  this.username = username;
  this.password = password;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public long getId() {
  return id;
 }

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

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 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;
 }
  }

Create data in Hibernate

Create a session factory object and configure hibernate configuration file and entity class SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Users.class).buildSessionFactory();

Get current session using Session session = factory.getCurrentSession();Save data object on the current session session.save(obj)In the Below example, we have created a user object and saved it on the current session. that contains the information that the user enters from the console. like Username, Password, FirstName, and LastName.

package com.CbHibEample;

import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.sql.ordering.antlr.Factory;

import com.cbhibexample.entity.Users;


public class Main {
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Users.class).buildSessionFactory();
  Session session = factory.getCurrentSession();
  try {
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter Username");
   String username = sc.nextLine(); 
   
   System.out.println("Enter Password");
   String password = sc.nextLine(); 
   
   System.out.println("Enter firstName");
   String firstName = sc.nextLine();
   
   System.out.println("Enter Last Name");
   String lastName = sc.nextLine(); 
   
   session.beginTransaction();
   //Save Data 
   Users user = new Users(username, password, firstName, lastName);
   session.save(user);
            System.out.println("Congrates Data is Created in database............");		
   
   session.getTransaction().commit();			

  } finally {
   // TODO: handle finally clause
   //session.close();
   //factory.close();
  }
  
  
 
   
  
 }
}

Read data in Hibernate

There are 3 kind of data that we need to read from the database.

Data of a specific row(data of nth number)

get() method is used to get the data of fix row session.get(Users.class, 2); will return the data of 2nd row.

Read the data of complete table

To read all the rows of the database table we need to use Hibernate query language (HQL) In the below example, we are using a custom HQL query to get the list of users List<Users> userList = session.createQuery("from users").list();

package com.CbHibEample;

import java.util.List;
import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.sql.ordering.antlr.Factory;

import com.cbhibexample.entity.Users;


public class Main {
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Users.class).buildSessionFactory();
  Session session = factory.getCurrentSession();
  try {
  
   session.beginTransaction();
              
            List<Users> userList =  session.createQuery("from users").list();
            System.out.println("...........User data..........");
            for (Users temp : userList) {
    System.out.println(temp);
   }
   session.getTransaction().commit();			

  } finally {
   // TODO: handle finally clause
   //session.close();
   //factory.close();
  }
  
  
 
   
  
 }
}

Read the data with conditions

where clause is used to get the data from a table on the basis of some conditions like I need the information of the user whose name “ABC”. this is similar to SQL but HQL is more easy and flexible in the below code we are trying to get the information of the user whose id is 1 by using HQL query from users where id='1'

Read data in hibernate using where clause

package com.CbHibEample;

import java.util.List;
import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.sql.ordering.antlr.Factory;

import com.cbhibexample.entity.Users;


public class Main {
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Users.class).buildSessionFactory();
  Session session = factory.getCurrentSession();
  try {
  
   session.beginTransaction();
              
            List<Users> userList =  session.createQuery("from users where id='1'").list();
            System.out.println("...........User data..........");
            for (Users temp : userList) {
    System.out.println(temp);
   }
   session.getTransaction().commit();			

  } finally {
   // TODO: handle finally clause
   //session.close();
   //factory.close();
  }
  
  
 
   
  
 }
}

Update data in Hibernate

package com.CbHibEample;

import java.util.List;
import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.sql.ordering.antlr.Factory;

import com.cbhibexample.entity.Users;


public class Main {
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Users.class).buildSessionFactory();
  Session session = factory.getCurrentSession();
  try {
  
   session.beginTransaction();
      //Update user name
   session.createQuery("update from users set username='Vihu'").executeUpdate();
         
   session.getTransaction().commit();			

  } finally {
   // TODO: handle finally clause
   //session.close();
   //factory.close();
  }   
 }
}

Update data in hibernate using where clause

session.createQuery("update from users set username='kihu' where id='1'").executeUpdate();

Delete data in Hibernate

package com.CbHibEample;

import java.util.List;
import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.sql.ordering.antlr.Factory;

import com.cbhibexample.entity.Users;


public class Main {
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Users.class).buildSessionFactory();
  Session session = factory.getCurrentSession();
  try {
  
   session.beginTransaction();
      //Update user name
   session.createQuery("delete from users where id='2'").executeUpdate();
         
   session.getTransaction().commit();			

  } finally {
   // TODO: handle finally clause
   //session.close();
   //factory.close();
  }     
 }
}

To understand Read, Update, and Delete operation in depth. you just need to understand the HQL in detail here is the HQL tutorial in detail.