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.
How do I bootstrap Hibernate in my Spring Boot application?
Don’t want to read? You can watch it here!
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;
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
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
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 as a paperback, ebook or PDF.