How to read data from database using hibernate

create a simple java application using hibernate to read data from the database. In the below hibernate example we are using the MYSQL database. you can use any database you just need to update the configuration to change the database connection.

Yes, To read the data we must have to insert the data into the database, here is a separate example to insert data into hibernate.

Steps to read data in hibernate

  1. Add dependency for Hibernate and MySQL connector in the project(pom.xml)
  2. Create Hibernate configuration file (hibernate.cfg.xml)
  3. Create Entity Class
  4. Configure Session Factory and Session and start the transections

Add dependency for Hibernate

Below is the maven dependency that you need to add to the pom.xml 

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

Create hibernate configuration file (hibernate.cfg.xml)

 create an XML file and keep this file in the src folder also the name “hibernate.cfg.xml” is not important to be the same but yes to follow the standards will recommend keeping the same name.

<?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

A simple java class can be an entity class by using annotation @Entity that is used to create a mapping between a class and database table.

Below are some important annotations that we use in Entity class with hibernate.

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

Read data from MySQL database using hibernate

Create a java main class (Main.java ) and create an object of SessionFactory and configure the session

SessionFactory factory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Users.class) .buildSessionFactory(); Session session = factory.getCurrentSession();

Create an object of Entity class(users), begin the transaction, Add data object into the database, Commit the transaction, and print response message.

package com.loginexample.utility;
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.loginexample.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 {			
 //Get Data
Users user = new Users();
session.beginTransaction();
user = (Users)session.get(Users.class, 2);
System.out.println(user);
session.getTransaction().commit();
   
  } finally {
   // TODO: handle finally clause
   session.close();
   factory.close();
  }

 }

}