Hibernate Tips: How to bootstrap Hibernate with Spring Boot


Take your skills to the next level!

The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.


Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question for a future Hibernate Tip, please leave a comment below.

Question:

How do I bootstrap Hibernate in my Spring Boot application?

Solution:

Spring Boot makes it extremely easy to bootstrap Hibernate. You just need to add the Spring Boot JPA starter to your classpath, and Spring Boot handles the bootstrapping for you.

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

You also need to add a database-specific JDBC driver to the classpath of your application. Please check your database documentation for more information.

You define your data source with a few properties in the application.properties file. The following configuration example defines a data source that connects to a PostgreSQL database on localhost.

spring.datasource.url = jdbc:postgresql://localhost:5432/recipes
spring.datasource.username = postgres
spring.datasource.password = postgres

If you add an H2, HSQL, or Derby database on the classpath, you can safely omit the configuration, and Spring Boot starts and connects to an in-memory database. You can also add multiple JDBC drivers and an in-memory database to your classpath and use different configurations for different target environments.

That’s all you need to do bootstrap Hibernate in a Spring Boot application. You can now use the @Autowired annotation to inject an EntityManager.

@Autowired
private EntityManager em;

Learn More

JPA and Hibernate also provide their own bootstrapping APIs. I explain Hibernate’s native API in more detail in: Hibernate Tip: How to use Hibernate’s native bootstrapping API.

Hibernate Tips Book

Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.

Get it now!

Leave a Reply

Your email address will not be published. Required fields are marked *

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