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 application.properties file, we are using h2 database to reduce unnecessary complexity.
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.5.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
  <java.version>1.8</java.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

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.

@Entity
@Table(name="TBL_EMPLOYEES")
public class EmployeeEntity {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    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.

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

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

spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

# Enabling H2 Console
spring.h2.console.enabled=true

# Custom H2 Console URL
spring.h2.console.path=/h2-console

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 application.properties file.

#Turn Statistics on and log SQL stmts

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

#If want to see very extensive logging
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.type=trace
logging.level.org.hibernate.stat=debug

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

spring.jpa.hibernate.ddl-auto=none

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

DROP TABLE IF EXISTS TBL_EMPLOYEES;

CREATE TABLE TBL_EMPLOYEES (
    id INT AUTO_INCREMENT  PRIMARY KEY,
    first_name VARCHAR(250) NOT NULL,
    last_name VARCHAR(250) NOT NULL,
    email VARCHAR(250) DEFAULT NULL
);
INSERT INTO TBL_EMPLOYEES
    (first_name, last_name, email)
VALUES
    ('Lokesh', 'Gupta', 'abc@gmail.com'),
    ('Deja', 'Vu', 'xyz@email.com'),
    ('Caption', 'America', 'cap@marvel.com');

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.

@SpringBootApplication
public class SpringBoot2DemoApplication implements CommandLineRunner {
 
    private Logger logger = LoggerFactory.getLogger(this.getClass());
     
    @Autowired
    EmployeeRepository repository;
     
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot2DemoApplication.class, args);
    }
 
    @Override
    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)
 
Hibernate: 
    select
        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_ 
    from
        tbl_employees employeeen0_ 
    where
        employeeen0_.id=?
 
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 the comments sections related to configuring hibernate with spring boot.

Happy Learning !!

Sourcecode download

Comments

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

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode