简体   繁体   中英

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

spring.jpa.hibernate.ddl-auto = create

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

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.

So I would like a hybrid mode. My models are still populated automatically - but I can call custom ddl code afterwards to create views.

Could someone help me?

you could inject Springs JdbcTemplate into your createTestEntries() method and use it to execute custom SQL to create your view:

@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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM