How to generate a ddl creation script with a modern Spring Boot + Data JPA and Hibernate setup?

Casey picture Casey · May 1, 2016 · Viewed 49.6k times · Source

Currently, I'm using the default @SpringBootApplication annotation with the following properties in application.properties:

spring.datasource.url=jdbc:mysql://localhost/dbname
spring.datasource.username=X
spring.datasource.password=X
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.naming_strategy=my.package.CustomNamingStrategy

Since JPA 2.1, I should be able to use the javax.persistence.schema-generation.* properties, but setting them in my application.properties seems to have no effect.

I've seen examples like this that wire up a whole bunch of extra beans, but they aren't using Mysql. And in any case, doing it like that requires me to configure many options that spring is taking care of for me now.

My goals are to:

  • Generate a schema creation sql script in the MYSQL dialect
  • without a database connection being required
  • Output the script in the build directory
  • Also generating hibernate envers tables would be a huge plus.

I do not want to:

  • Create/drop schemas on a live database

Lib versions:

   hibernate          : 4.3.11.FINAL
   spring framework   : 4.2.5.RELEASE
   spring-boot        : 1.3.3.RELEASE
   spring-data-jpa    : 1.10.1.RELEASE   // for  querydsl 4 support
   spring-data-commons: 1.12.1.RELEASE   // for  querydsl 4 support

(Using gradle, not maven)

Answer

Casey picture Casey · May 1, 2016

Ah, right after I posted this question a section of the spring data docs caught my eye:

73.5 Configure JPA properties In addition all properties in spring.jpa.properties.* are passed through as normal JPA properties (with the prefix stripped) when the local EntityManagerFactory is created.

So, to answer my own question: prefix the javax.persistence properties with spring.jpa.properties:

spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql

After doing this, the schema file was generated automatically in the project root.