Spring Boot with Hibernate Example

Welcome readers, in this tutorial, we will integrate Hibernate with a Spring Boot application.

1. Introduction

  • Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides a powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases

1.1 What is Hibernate?

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides the reference implementation of the Java Persistence API that makes it a great choice as an ORM tool with benefits of loose coupling
  • A Framework that an option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well as XML based configuration

Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot.

2. Spring Boot with Hibernate Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL, and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Spring Boot with Hibernate - Application Structure
Fig. 1: Application Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Boot with Hibernate - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Boot with Hibernate - Project Details
Fig. 3: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring Boot with Hibernate - Archetype Selection
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:


<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Let’s start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application. But before starting we are assuming that developers have installed the MySQL on their machine.

3.1 Maven Dependencies

Here, we specify the dependencies for the Spring Boot and MySQL. Maven will automatically resolve the other dependencies. The updated file will have the following code.


<project xmlns=""

	<name>Springboot hibernate tutorial</name>




3.2 Configuration Files

Create a new properties file at the location: Springboothibernatetutorial/src/main/resources/ and add the following code to it.

# Application configuration.

# Local mysql database configuration.
datasource.url= jdbc:mysql://localhost:3306/springhibernatedb
datasource.username= root

# Hibernate configuration.

# Package to scan.
packagesToScan= jcg

3.3 Java Classes

Let’s write all the java classes involved in this application.

3.3.1 Implementation/Main class

Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.

package jcg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

 * Main implementation class which serves two purpose in a spring boot application: Configuration and bootstrapping.
 * @author yatin-batra
public class Myapplication {

	public static void main(String[] args) {, args);

3.3.2 Hibernate configuration

Add the following code to the Hibernate configuration to initialize the Hibernate’s Session-factory object and handle the sql operations.

package jcg.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

public class HibernateConfig {

	private Environment env;

	public LocalSessionFactoryBean sessionFactory() {
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

		return sessionFactory;

	public DataSource dataSource() {
		DriverManagerDataSource  ds = new DriverManagerDataSource ();

		return ds;

	private final Properties hibernateProperties() {
		Properties hibernate = new Properties();
		hibernate.setProperty("", env.getProperty(""));
		hibernate.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
		hibernate.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));

		return hibernate;

3.3.3 Model class

Add the following code to the product model class.

package jcg.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;

// Model class.
@Table(name = "book")
public class Book {

	@GeneratedValue(strategy= GenerationType.IDENTITY)
	private int id;
	private String title;
	private String author;

	public Book() { }

	public int getId() {
		return id;
	public void setId(int id) { = id;
	public String getTitle() {
		return title;
	public void setTitle(String title) {
		this.title = title;
	public String getAuthor() {
		return author;
	public void setAuthor(String author) { = author;

3.3.4 Data-Access-Object class

Add the following code the Dao class designed to handle the database interactions. The class is annotated with the @Repository annotation.

package jcg.repository;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import jcg.model.Book;

// Database repository class.
public class BookDao {

	private SessionFactory sf;

	// Save book in the db.
	public Integer createBook(Book book) {
		Session s = sf.getCurrentSession();
		Integer id = (Integer);
		return id;

	// Get all books.
	@SuppressWarnings({ "deprecation", "unchecked" })
	public List<Book> findAll() {
		Session s = sf.getCurrentSession();
		List<Book> list = s.createCriteria(Book.class).list();
		return list;

	// Find book by id.
	public Book findById(int bookid) {
		Session s = sf.getCurrentSession();
		Book book = s.get(Book.class, bookid);
		return book;

3.3.5 Controller class

Add the following code to the controller class designed to handle the incoming requests. The class is annotated with the @RestController annotation where every method returns a domain object as a json response instead of a view.

package jcg.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jcg.model.Book;
import jcg.repository.BookDao;

// Controller class.
public class BookCtrl {

	private BookDao bookdao;

	// Create a new record in database.
	@PostMapping(value= "/create")
	public ResponseEntity<Book> create(@RequestBody Book book) {
		int id = bookdao.createBook(book);
		if(id != 0)
			return new ResponseEntity<Book>(HttpStatus.CREATED);

		return new ResponseEntity<Book>(HttpStatus.INTERNAL_SERVER_ERROR);

	// Fetch all books from the database.
	@GetMapping(value= "/getall")
	public ResponseEntity<List<Book>> findAll() {
		return ResponseEntity.ok(bookdao.findAll());

	// Fetch particular book from the database.
	@GetMapping(value= "/get/{id}")
	public ResponseEntity<Book> getBookById(@PathVariable("id") int bookid) {
		Book book = bookdao.findById(bookid);
		if(book == null)
			return new ResponseEntity<Book>(HttpStatus.NOT_FOUND);

		return new ResponseEntity<Book>(book, HttpStatus.OK);

4. Run the Application

As we are ready with all the changes, let us compile the spring boot project and run the application as a java project. Right click on the class, Run As -> Java Application.

Spring Boot with Hibernate - Run
Fig. 6: Run the Application

Developers can debug the example and see what happens after every step. Enjoy!

5. Project Demo

Open the postman tool and hit the following urls to display the data in the json format.

// Create book

// Get all books

// Get book by id

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to integrate Hibernate with Spring Boot application and perform the basic sql operations. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of implementing Hibernate in Spring Boot.

You can download the full source code of this example here: Spring Boot with Hibernate Example


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button