Spring Boot JPA Configuration

Spring Boot configures Hibernate as the default JPA provider, so it’s no

longer necessary to define the entityManagerFactory bean unless we want

to customize it.

Spring Boot can also auto-configure the dataSource bean, depending on

the database we’re using. In the case of an in-memory database of type H2,

HSQLDB and Apache Derby, Boot automatically configures the DataSource

if the corresponding database dependency is present on the classpath.

For example, if we want to use an in-memory H2 database in a Spring Boot

JPA application, we only need to add the h2 dependency to the pom.xml file:

<dependency>

    <groupId>com.h2database</groupId>

    <artifactId>h2</artifactId>

    <version>1.4.197</version>

</dependency>

This way, we don’t need to define the dataSource bean, but we can do so if

we want to customize it.

If we want to use JPA with MySQL database, then we need the

mysql-connector-java dependency, as well as to define the DataSource

configuration.

We can do this in a @Configuration class, or by using standard Spring Boot

properties.

The Java configuration looks the same as it does in a standard Spring project:

@Bean

public DataSource dataSource() {

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName(“com.mysql.cj.jdbc.Driver”);

dataSource.setUsername(“mysqluser”);

dataSource.setPassword(“mysqlpass”);

dataSource.setUrl(

“jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true”);

return dataSource;

}

To configure the data source using a properties file, we have to set properties

prefixed with spring.datasource:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.username=mysqluser

spring.datasource.password=mysqlpass

spring.datasource.url=

jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true

However, if we have a standard Spring project(this means that instead of Spring Boot, it's the normal Spring Framework), then we need more explicit

configuration, using either Java or XML. That’s what we’ll focus on in the

next sections.

 

Comments

Popular posts from this blog

Hibernate Many to Many Relationship

Why Integral Calculus limit tending to infinity a sacrilege

Introduction