lundi 30 mai 2022

Spring Initialize a Database Using Hibernate datasource configuration

I can't believe this the default mode configuration with hibernate, in our test everytime hibernate is dropping the table  and recreating it on every execution of Spring, so we lost the data. 

If an embedded database is identified and no schema manager (Flyway or Liquibase) has been detected, ddl-auto defaults to create-drop

refere to : https://docs.spring.io/spring-boot/how-to/data-initialization.html

How to tell to Spring Don't do that, please :) ?

jpa:
hibernate:
ddl-auto:update # don't remove anything


In production, spring.jpa.hibernate.ddl-auto should be disabled (not specified) or set to validate, and the database migration should be managed via dedicated tools such as Flyway or Liquibase


jpa:
hibernate:
ddl-auto:none

This allow our schema file to create the repository, instead to allowing hibernate to do it.

But for setting h2 for test 

spring.jpa.hibernate.ddl-auto property is not explicitly configured, Spring Boot uses create-drop for embedded databases such as H2 by default

Note: It is strongly recommended to set the spring.jpa.hibernate.ddl-auto property to none in a production environment—this prevents Spring Data JPA to manipulate the structure of the SQL tables.

jpa:
hibernate:
ddl-auto: create-drop

 spring:

  # [ Base fichier H2 ]
datasource:
platform: h2
url: jdbc:h2:./test-h2/test-db;DB_CLOSE_DELAY=-1;MODE=Oracle;TRACE_LEVEL_FILE=4;AUTO_SERVER=TRUE
driver-class-name: org.h2.Driver
username: sa
password:
h2:
console:
path: /manage/h2/console
enabled: true
jpa:
hibernate:
ddl-auto: create-drop
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect