Boot

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:

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>jcg.tutorial</groupId>
	<artifactId>Springboothibernatetutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

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.

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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jcg.tutorial</groupId>
	<artifactId>Springboothibernatetutorial</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<name>Springboot hibernate tutorial</name>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
	</dependencies>

	<build>
		<finalName>Springboothibernatetutorial</finalName>
	</build>
</project>

3.2 Configuration Files

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

application.properties

# Application configuration.
server.port=8102

# Local mysql database configuration.
datasource.driver-class-name=com.mysql.cj.jdbc.Driver
datasource.url= jdbc:mysql://localhost:3306/springhibernatedb
datasource.username= root
datasource.password=

# Hibernate configuration.
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

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

Myapplication.java

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
 */
@SpringBootApplication
public class Myapplication {

	public static void main(String[] args) {
		SpringApplication.run(Myapplication.class, 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.

HibernateConfig.java

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;

@Configuration
public class HibernateConfig {

	@Autowired
	private Environment env;

	@Bean
	public LocalSessionFactoryBean sessionFactory() {
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());
		sessionFactory.setPackagesToScan(env.getProperty("packagesToScan"));
		sessionFactory.setHibernateProperties(hibernateProperties());

		return sessionFactory;
	}

	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource  ds = new DriverManagerDataSource ();
		ds.setDriverClassName(env.getProperty("datasource.driver-class-name"));
		ds.setUrl(env.getProperty("datasource.url"));
		ds.setUsername(env.getProperty("datasource.username"));
		ds.setPassword(env.getProperty("datasource.password"));

		return ds;
	}

	private final Properties hibernateProperties() {
		Properties hibernate = new Properties();
		hibernate.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
		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.

Book.java

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.
@Entity
@Table(name = "book")
public class Book {

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

	public Book() { }

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.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) {
		this.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.

BookDao.java

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.
@Repository
public class BookDao {

	@Autowired
	private SessionFactory sf;

	// Save book in the db.
	public Integer createBook(Book book) {
		Session s = sf.getCurrentSession();
		
		s.beginTransaction();
		Integer id = (Integer) s.save(book);
		s.getTransaction().commit();
		
		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.

BookCtrl.java

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.
@RestController
@RequestMapping(value="/springhibernateapi")
public class BookCtrl {

	@Autowired
	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 Myapplication.java 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
http://localhost:8102/springhibernateapi/create

// Get all books
http://localhost:8102/springhibernateapi/getall

// Get book by id
http://localhost:8102/springhibernateapi/get/1

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.

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

Yatin

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).
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button