[英]How to run a custom ddl script on startup of Spring Boot 2
Is it possible to run a custom ddl script on startup after 是否可以在启动后在启动时运行自定义ddl脚本
spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.ddl-auto =创建
has created the model entities in the database? 在数据库中创建了模型实体?
Currently I do a lot of changes to the models and want to drop everything after a change and create Test data via: 目前,我对模型做了很多更改,并希望更改后删除所有内容,并通过以下方式创建测试数据:
@Bean
InitializingBean createTestEntries() {
return () -> {
testObject t1 = new testObject (values...);
testRepo.save(t1);
}
After that I want to create a database view, but I don't find a way to do that with Spring Boot 2 + Hibernate/JPA 之后,我想创建一个数据库视图,但是我找不到使用Spring Boot 2 + Hibernate / JPA做到这一点的方法。
Of course I could disable ddl-auto and do everything with a schema.sql and data.sql file - but It's very comfortable that my model changes are populated automatically to the db. 当然,我可以禁用ddl-auto并使用schema.sql和data.sql文件执行所有操作-但很高兴将我的模型更改自动填充到db中。
So I would like a hybrid mode. 所以我想要一个混合模式。 My models are still populated automatically - but I can call custom ddl code afterwards to create views.
我的模型仍会自动填充-但之后我可以调用自定义ddl代码来创建视图。
Could someone help me? 有人可以帮我吗?
you could inject Springs JdbcTemplate into your createTestEntries() method and use it to execute custom SQL to create your view: 您可以将Springs JdbcTemplate注入到createTestEntries()方法中,并使用它执行自定义SQL来创建视图:
@Bean
InitializingBean createTestEntries(@Autwired JdbcTemplate jdbc) {
return () -> {
testObject t1 = new testObject (values...);
testRepo.save(t1);
jdbc.update("custom SQL here")
}
Depending on your needs you could alternatively inject the DataSource or EntityManager (using native queries) and use that. 根据您的需要,您也可以注入DataSource或EntityManager(使用本机查询)并使用它。
EDIT: native query example 编辑:本机查询示例
@Bean
InitializingBean createTestEntries(@Autowired EntityManager em) {
return () -> {
Query q = em.createNativeQuery("custom sql");
q.executeUpdate()
}
}
see JPA API Docs for more details: 有关更多详细信息,请参见JPA API文档 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.