The Spring Framework provides extensive support for working with SQL databases. From
direct JDBC access using JdbcTemplate
to complete “object relational mapping”
technologies such as Hibernate. Spring Data provides an additional level of functionality,
creating Repository
implementations directly from interfaces and using conventions to
generate queries from your method names.
Java’s javax.sql.DataSource
interface provides a standard method of working with
database connections. Traditionally a DataSource uses a URL
along with some
credentials to establish a database connection.
It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.
Tip | |
---|---|
The “How-to” section includes a section on how to initialize a database |
Spring Boot can auto-configure embedded H2, HSQL and Derby databases. You don’t need to provide any connection URLs, simply include a build dependency to the embedded database that you want to use.
For example, typical POM dependencies would be:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <scope>runtime</scope> </dependency>
Note | |
---|---|
You need a dependency on |
Production database connections can also be auto-configured using a pooling
DataSource
. Here’s the algorithm for choosing a specific implementation.
DataSource
for its performance and concurrency, so if
that is available we always choose it.
If you use the spring-boot-starter-jdbc
or spring-boot-starter-data-jpa
“starter POMs” you will automcatically get a dependency to tomcat-jdbc
.
Note | |
---|---|
Additional connection pools can always be configured manually. If you define your
own |
DataSource configuration is controlled by external configuration properties in
spring.datasource.*
. For example, you might declare the following section
in application.properties
:
spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driverClassName=com.mysql.jdbc.Driver
See AbstractDataSourceConfiguration
for more of the supported options.
Note | |
---|---|
For a pooling |
Spring’s JdbcTemplate
and NamedParameterJdbcTemplate
classes are auto-configured and
you can @Autowire
them directly into your own beans:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final JdbcTemplate jdbcTemplate; @Autowired public MyBean(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } // ... }
The Java Persistence API is a standard technology that allows you to “map” objects to
relational databases. The spring-boot-starter-data-jpa
POM provides a quick way to get
started. It provides the following key dependencies:
Tip | |
---|---|
We won’t go into too many details of JPA or Spring Data here. You can follow the “Accessing Data with JPA” guide from http://spring.io and read the Spring Data JPA and Hibernate reference documentation. |
Traditionally, JPA “Entity” classes are specified in a persistence.xml
file. With
Spring Boot this file is not necessary and instead “Entity Scanning” is used. By
default all packages below your main configuration class (the one annotated with
@EnableAutoConfiguration
) will be searched.
Any classes annotated with @Entity
, @Embeddable
or @MappedSuperclass
will be
considered. A typical entity class would look something like this:
package com.example.myapp.domain; import java.io.Serializable; import javax.persistence.*; @Entity public class City implements Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private String state; // ... additional members, often include @OneToMany mappings protected City() { // no-args constructor required by JPA spec // this one is protected since it shouldn't be used directly } public City(String name, String state) { this.name = name; this.country = country; } public String getName() { return this.name; } public String getState() { return this.state; } // ... etc }
Tip | |
---|---|
You can customize entity scanning locations using the |
Spring Data JPA repositories are interfaces that you can define to access data. JPA
queries are created automatically from your method names. For example, a CityRepository
interface might declare a findAllByState(String state)
method to find all cities
in a given state.
For more complex queries you can annotate your method using Spring Data’s
Query
annotation.
Spring Data repositories usually extend from the
Repository
or
CrudRepository
interfaces. If you are using
auto-configuration, repositories will be searched from the package containing your
main configuration class (the one annotated with @EnableAutoConfiguration
) down.
Here is a typical Spring Data repository:
package com.example.myapp.domain; import org.springframework.data.domain.*; import org.springframework.data.repository.*; public interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); }
Tip | |
---|---|
We have barely scratched the surface of Spring Data JPA. For complete details check their reference documentation. |
By default JPA database will be automatically created only if you use an embedded
database (H2, HSQL or Derby). You can explicitly configure JPA settings using
spring.jpa.*
properties. For example, to create and drop tables you can add the
following to your application.properties
.
spring.jpa.hibernate.ddl-auto=create-drop
Note | |
---|---|
Hibernate’s own internal property name for this (if you happen to remember it
better) is |