Configure Hibernate with Spring Boot

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

If you do not have a project structure ready then you should first create a new Spring Boot project.

1. Project Dependencies

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

  • 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 file, we are using h2 database to reduce unnecessary complexity.
  <relativePath /> <!-- lookup parent from repository -->






2. Creating JPA Entities

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

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

Starting Hibernate 6 and Spring Boot 3, we should import Jakarta persistence annotations from package jakarta.persistence.*. Both have moved to Jakarta EE in the new releases.

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.
  • 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 the entity class e.g. in the 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 overriding toString() method to print employee’s basic details in logs.

Read More : JPA Annotations

3. Creating JPA Repository

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

public interface EmployeeRepository 
  extends JpaRepository<EmployeeEntity, Long> {

By this simple extension, EmployeeRepository inherits several methods for working with EmployeeEntity persistence, including methods for saving, deleting, and finding EmployeeEntity .rows from the database

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 file which will help in connecting the database to JPA code.

In the given configuration, we are configuring the h2 database.


# Enabling H2 Console

# Custom H2 Console URL

4.2. Enable SQL Logging for Debugging Purposes

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 entries in file.

#Turn Statistics on and log SQL stmts

#If want to see very extensive logging

4.3. Schema and Data 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 we are using schema.sql.

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


Now create data.sql for schema creation and data.sql to insert some initial data into the tables.


    first_name VARCHAR(250) NOT NULL,
    last_name VARCHAR(250) NOT NULL,
    (first_name, last_name, email)
    ('Lokesh', 'Gupta', ''),
    ('Deja', 'Vu', ''),
    ('Caption', 'America', '');

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

public class SpringBoot2DemoApplication implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    EmployeeRepository repository;
    public static void main(String[] args) {, args);
    public void run(String... args) throws Exception 
        Optional<EmployeeEntity> emp = repository.findById(2L);
"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: 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' is enabled by default. Therefore, database queries may be performed during view rendering. 
Explicitly configure 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)
    select as id1_0_0_, 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,]

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

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

Happy Learning !!

Sourcecode download


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.