Spring boot hibernate configuration example

Learn to configure hibernate/JPA support in Spring Boot2 applications, along with creating entity classes and extending inbuilt JpaRepository interfaces.

1. Maven Dependencies

In this example, we are using maven to add runtime jars in project. If you are using gradle then please find related dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        <relativePath /> <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot</description>







  • spring-boot-starter-data-jpa (required) : It includes spring data, hibernate, HikariCP, JPA API, JPA Implementation (default is hibernate), JDBC and other required libraries.
  • h2 : Though we can add any database easily using datasource properties in application.properties file, we are using h2 database in reduce unnecessary complexity.

2. Create JPA entity classes

After we have included required jars in classpath, create few entity classes as per project needs. We are here creating one such entity EmployeeEntity for example purpose.

Remember to include only JPA API annotations (javax.persistence.*) to decouple hibernate from application code.

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

public class EmployeeEntity {

    private Long id;
    private String firstName;
    private String lastName;
    @Column(name="email", nullable=false, length=200)
    private String email;
    //Setters and getters left out for brevity.

    public String toString() {
        return "EmployeeEntity [id=" + id + ", firstName=" + firstName + 
                ", lastName=" + lastName + ", email=" + email   + "]";
  • We do not need to do anything to make this class scannable. Spring boot will look for all @Entity annotated classes and configure them by default as JPA entities.
  • By default the name of the table is the name of entity class e.g. in above case it shall be EmployeeEntity. We can customize the table name using @Table annotation and it’s name attribute.
  • The id property is annotated with @Id so that JPA will recognize it as the object’s ID. Also, @GeneratedValue annotation enable its value generated automatically.
  • To customize the name of columns, null value allowed or size of column etc. use @Column annotation.
  • I will suggest to override toString() method to print employee’s basic details in logs.

Read More : JPA Annotations

3. Create JPA Repository

Extend JpaRepository interface to allows to create repository implementations automatically, at runtime, for any given entity class. The types of entity class and it’s ID field are specified in the generic parameters on JpaRepository.

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.howtodoinjava.demo.entity.EmployeeEntity;

public interface EmployeeRepository extends JpaRepository<EmployeeEntity, Long> {


By this simple extension, EmployeeRepository inherits several methods for working with Employee persistence, including methods for saving, deleting, and finding Employee entities.

Along with default provided methods, we can add our own custom methods and queries to this interface.

4. Properties Configuration

4.1. Data source

Provide the datasource connection properties in application.properties file which will help in connecting the database to JPA code.

In given config, we are configuring h2 database.


# Enabling H2 Console

# Custom H2 Console URL

4.2. Hibernate print SQL and Logging

A good way to see how the components are working – is to enable extensive logging. Do it when it’s too easy using only few properties entries.

#Turn Statistics on and log SQL stmts


#If want to see very extensive logging

4.3. Database Initialization

In a JPA-based applications, we can either choose to let Hibernate create the schema using entity classes or use schema.sql, but we cannot do both.

Make sure to disable spring.jpa.hibernate.ddl-auto if using schema.sql.

#Schema will be created using schema.sql and data.sql files

    first_name VARCHAR(250) NOT NULL,
    last_name VARCHAR(250) NOT NULL,
    (first_name, last_name, email) 
    ('Lokesh', 'Gupta', 'abc@gmail.com'),
    ('Deja', 'Vu', 'xyz@email.com'),
    ('Caption', 'America', 'cap@marvel.com');

5. Spring boot hibernate demo

To test hibernate configuration with Spring boot, we need to autowire the EmployeeRepository dependency in a class and use it’s method to save or fetch employee entities.

Let’s do this testing in @SpringBootApplication annotated class and using CommandLineRunner interface. The run() method from CommandLineRunner is executed immediately after the application startup.

package com.howtodoinjava.demo;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.howtodoinjava.demo.entity.EmployeeEntity;
import com.howtodoinjava.demo.repository.EmployeeRepository;

public class SpringBoot2DemoApplication implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    EmployeeRepository repository;
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot2DemoApplication.class, args);

    public void run(String... args) throws Exception 
        Optional<EmployeeEntity> emp = repository.findById(2L);

        logger.info("Employee id 2 -> {}", emp.get());

Run the application and observe the output. Please note that to print limited information in logs, I am using property logging.pattern.console=%m%n in application

Tomcat initialized with port(s): 8080 (http)
Starting service [Tomcat]
Starting Servlet engine: [Apache Tomcat/9.0.19]
Initializing Spring embedded WebApplicationContext
Root WebApplicationContext: initialization completed in 5748 ms

HikariPool-1 - Starting...
HikariPool-1 - Start completed.
HHH000204: Processing PersistenceUnitInfo [
    name: default
HHH000412: Hibernate Core {5.3.10.Final}
HHH000206: hibernate.properties not found
HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
HHH000400: Using dialect: org.hibernate.dialect.H2Dialect

Initialized JPA EntityManagerFactory for persistence unit 'default'
Initializing ExecutorService 'applicationTaskExecutor'
spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. 
Explicitly configure spring.jpa.open-in-view to disable this warning
Tomcat started on port(s): 8080 (http) with context path ''
Started SpringBoot2DemoApplication in 17.638 seconds (JVM running for 19.1)

        employeeen0_.id as id1_0_0_,
        employeeen0_.email as email2_0_0_,
        employeeen0_.first_name as first_na3_0_0_,
        employeeen0_.last_name as last_nam4_0_0_ 
        tbl_employees employeeen0_ 

Employee id 2 -> EmployeeEntity [id=2, firstName=Deja, lastName=Vu, email=xyz@email.com]

Clearly, hibernate has been configured and we are able to interact with database using JPA repository interface.

Drop me your questions in comments sections related to configuring hibernate with spring boot.

6. Spring boot hibernate tutorials

  1. Spring boot crud operations example with hibernate
  2. Spring Boot CRUD Application with Thymeleaf and Hibernate

  3. Spring boot pagination and sorting example

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

4 thoughts on “Spring boot hibernate configuration example”

  1. @Repository
    should not be used for the Interface it should be used for class
    In your code u have used it for Interface

    public interface EmployeeRepository extends JpaRepository {


  2. Hi. Should my Entity class always has Getter and Setter method? Because when I don’t put getter and setter. The localhost always shows the empty json, which has nothing inside that ” { } ” .

  3. when i am trying to hit the url “http://localhost:8080/employees” as post method i am getting error as below:

    “status”: 500,
    “error”: “Internal Server Error”,
    “message”: “The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!”,”

    in body i am passing the value as below :



    • For a new entity the id mst always be null because the @Id generates a unique ID according to the sequence generator mentioned in the annotation.


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.