Database support - apinazo/booter GitHub Wiki
This shows how to add a simple datasource to the project.
To have this working, we'll need to import the starter-data-jpa
dependency. It adds DB support, JPA and autoconfigured datasources. Moreover adds HikariCP connection pool, preferred by Spring Boot by its high performance.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
An in memory DB is very useful for tests. In Booter it's also used as a default database for the application - unless a different datasource is defined.
If Spring Boot developer tools are in the classpath the H2 web console will be enabled at the endpoint /h2-console
, with the user and password defined in the datasource.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>`
A real DB could be MySQL. Importing the connector allows defining a datasource for this DB.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Spring Data JPA it's configured as shown below. Maybe the most important property is ddl-auto
which says what to do with the DB at application startup: update it, create new tables and relationships, or drop them all and create everything after that.
spring:
jpa:
hibernate:
show-sql: false # Hide Hibernate logs but if log level is DEBUG this will be ignored.
format-sql: true # Beautify ugly Hibernate queries.
ddl-auto: update # none, update, create, create-drop.
By default, only a single datasource is configured in a Spring Boot application and it will be on a bean of type Datasource
, with the name datasource
. It can be injected where needed.
spring:
datasource:
url: jdbc:h2:mem:~/test
username: sa
password:
driver-class-name: org.h2.Driver
This extract from the logging configuration shows how to do to make Hibernate to log SQL queries and besides log the real values used in the query parameters.
logging:
level:
org.hibernate.SQL: DEBUG # To show SQL queries.
org.hibernate.type.descriptor.sql.BasicBinder: TRACE # And their param values.