title: Spring - execute query before application shutdown (tests)
body: <p>I'm running SpringBoot 2.1 with Sprind Data JPA/Hibernate as persistence layer. I run into problem to succesfully run query, <em>in my tests</em>, before application shutdown.</p>
  
  <p>Details:</p>
  
  <p>During application context startup I'm executing a query via JPA (let's say this query translates to following SQL <code>"insert into mytable('mycolumn') values ('abc')</code>).</p>
  
  <p>Now I need to execute another query before application is shutdown. For given example this would be <code>"update mytable set mycolumn = 'xyz' where mycolumn = 'abc'</code></p>
  
  <p>I managed to execute the query by using @PreDestroy on my configuration class</p>
  
  <pre><code>@Configuration
  MyConfig {
  
     @Autowired
     private MyTransactionalService myService;
  
     @PreDestroy
     public void doQuery() {
        mySerivce.runMyQuery(); 
  
    }
  }
  </code></pre>
  
  <p><code>mySerivce.runMyQuery()</code> delagates to <code>myRepository</code> (which is Spring Data JPA Repository) to call update query:</p>
  
  <pre><code>MyRepository extends JpaRepository(String, Something) {
  
     @Modifying
     @Query("UPDATE myEntity e SET e.myColumn = 'xyz' WHERE e.myColumn = 'abc")' 
     void runMyQuery();
  }
  </code></pre>
  
  <p>The method annotated with <code>@PreDestroy</code> 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.</p>
  
  <p>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). </p>
  
  <p>My guess would be that the shudtown process is in progress, so the in-memory database was cleared out... thus there is no table.</p>
  
  <p>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) ?  </p>