我使用Spring Boot with Hibernate。我在服务器重新加载时尝试删除MySQL表的所有内容。我知道这听起来很愚蠢,但我真的找不到办法,可能因为它听起来很愚蠢。有什么想法吗?
答案 0 :(得分:1)
由于您只想清除一个表而不是所有架构,因此无法使用ddl-auto属性。
我建议将该表的deleteAll逻辑添加到事件ContextRefreshedEvent上的ApplicationListener,您可以在其中使用所有spring bean(这与@PostConstructor的区别在于您可以这样做)因此您可以将此类注释为spring服务和使用自动装配
public class YourJobClass implements ApplicationListener<ContextRefreshedEvent>{
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
//Do your job
}
}
或者如果您不需要任何特定的东西,只需在任何类的@PostConstruct块中执行您的逻辑,尽管您需要在此特定情况下初始化所有上下文(@PostConstruct仅保证自动装配完成带注释的bean)
此处列出了事件http://www.logicbig.com/tutorials/spring-framework/spring-core/spring-events/
答案 1 :(得分:0)
如果要删除表格的所有内容,可以在 application.properties 中添加以下属性来执行此操作。 create
属性将在开始时创建所有表
spring.jpa.hibernate.ddl-auto=create