Search code examples
springspring-bootspring-data-jpashutdown-hookapplication-shutdown

Spring - execute query before application shutdown (tests)


I'm running SpringBoot 2.1 with Sprind Data JPA/Hibernate as persistence layer. I run into problem to succesfully run query, in my tests, before application shutdown.

Details:

During application context startup I'm executing a query via JPA (let's say this query translates to following SQL "insert into mytable('mycolumn') values ('abc')).

Now I need to execute another query before application is shutdown. For given example this would be "update mytable set mycolumn = 'xyz' where mycolumn = 'abc'

I managed to execute the query by using @PreDestroy on my configuration class

@Configuration
MyConfig {

   @Autowired
   private MyTransactionalService myService;

   @PreDestroy
   public void doQuery() {
      mySerivce.runMyQuery(); 

  }
}

mySerivce.runMyQuery() delagates to myRepository (which is Spring Data JPA Repository) to call update query:

MyRepository extends JpaRepository(String, Something) {

   @Modifying
   @Query("UPDATE myEntity e SET e.myColumn = 'xyz' WHERE e.myColumn = 'abc")' 
   void runMyQuery();
}

The method annotated with @PreDestroy executes but when the query is executed by H2 (inmemory db running inside my spring tests) it throws exception saying that table does not exist.

The thing is that table surely existed before as I'm able to execute INSERT on that table during application startup (see beginning of the post).

My guess would be that the shudtown process is in progress, so the in-memory database was cleared out... thus there is no table.

Is there anyway to ensure query is executed while connection to database is still healthy and removal of tables did not happen yet (upon application context shutdown) ?


Solution

  • I managed to overcome this by using DB_CLOSE_ON_EXIT=FALSE"; init parameter

    String url = "jdbc:h2:~/test;DB_CLOSE_ON_EXIT=FALSE";
    

    In this case H2 does not kill the database and keeps it available during the shutdown process.