Search code examples
jpaspring-data-jpaddl

Spring JPA DDL file generation - how to delete or clean file before generating


I am using this setup to generate a ddl file:

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=./ddl/schema.sql

The generation is executed via a specific test in Maven validation phase:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@TestPropertySource(locations = "/ddl.properties")
public class GenerateDDL {

    @Autowired
    private EntityManager em;

    @Test
    public void generateDDL() throws IOException {
        em.close();
        em.getEntityManagerFactory().close();
    }

}

This is working fine, with on problem: the generator does not create a new file but just appends always it's stuff.

Is there a way or setting to let generator always create a new file or clean up the old?

Deleting it within the test would delete it after generation. We also need the file to be published on git thus it is not generated within target.

UPDATE There seems at least no solution within Hibernate (until Hibernate 6): https://hibernate.atlassian.net/browse/HHH-11817

Is there a way to hook into Spring context creation - before persistence context is created? There i could delete the file.


Solution

  • TLDR: Assuming your spring boot project includes a version of Hibernate >= 5.5.3, then to configure the schema file(s) to be overwritten (i.e. disable appending) you would add this entry in your application.properties file:

    spring.jpa.properties.hibernate.hbm2ddl.schema-generation.script.append=false
    

    Since Hibernate version 5.5.3 there is a new property available that can be set to disable the appending behaviour. From the Hibernate User Guide:

    26.15. Automatic schema generation

    hibernate.hbm2ddl.schema-generation.script.append (e.g. true (default value) or false)

    For cases where the jakarta.persistence.schema-generation.scripts.action value indicates that schema commands should be written to DDL script file, hibernate.hbm2ddl.schema-generation.script.append specifies if schema commands should be appended to the end of the file rather than written at the beginning of the file. Values are true for appending schema commands to the end of the file, false for writing achema commands at the beginning of the file.