【问题标题】:Spring JPA DDL file generation - how to delete or clean file before generatingSpring JPA DDL 文件生成 - 如何在生成之前删除或清理文件
【发布时间】:2020-03-02 23:32:27
【问题描述】:

我正在使用这个设置来生成一个 ddl 文件:

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

生成是通过 Maven 验证阶段的特定测试执行的:

@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();
    }

}

这工作正常,但有一个问题:生成器不会创建新文件,而是总是附加它的东西。

有没有办法或设置让生成器始终创建新文件或清理旧文件?

在测试中删除它会在生成后删除它。我们还需要在 git 上发布文件,因此它不会在 target 中生成。

更新 Hibernate 中似乎至少没有解决方案(直到 Hibernate 6): https://hibernate.atlassian.net/browse/HHH-11817

有没有办法在创建持久性上下文之前挂钩 Spring 上下文创建?在那里我可以删除文件。

【问题讨论】:

  • 启动时使用maven删除文件?
  • 这将是一个糟糕的选择 - 如果从 maven 或 IDE 运行测试应该有相同的结果。但似乎没有其他选择?!

标签: jpa spring-data-jpa ddl


【解决方案1】:

我遇到了同样的问题,发现在生成模式之前清理的方法如下:使用 BeanFactoryPostProcessor。 BeanFactoryPostProcessor 在所有 bean 定义都被加载,但还没有实例化 bean 时被调用。

 /**
 * Remove auto-generated schema files before JPA generates them.
 * Otherwise new content will be appended to the files.
 */
@Configuration
public class SchemaSupport {

    @Bean
    public static BeanFactoryPostProcessor schemaFilesCleanupPostProcessor() {
        return bf -> {
            try {
                Files.deleteIfExists(Path.of("schema-drop-auto.sql"));
                Files.deleteIfExists(Path.of("schema-create-auto.sql"));
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        };
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 2018-08-31
    • 2022-11-15
    相关资源
    最近更新 更多