在应用程序关闭时删除没有支持域 类 的表

Dropping tables, with no backing domain classes, on application shutdown

我想在应用程序关闭时删除我在应用程序启动期间即时创建的表。这些没有 Domain 类。

我使用了 Bootstrap.groovy 中可用的 destroy 闭包,像这样

def someService
...
...
def destroy = {
    String dbCreate = Holders.grailsApplication.config.getProperty('dataSource.dbCreate', String)
    if(dbCreate == 'create-drop')
        someService.drop(customTables) // customTables is a List of names
}

drop() 服务中的方法看起来像,

void drop(List<String> tables) {
    Session session = sessionFactory.currentSession // Getting exception on this line
    tables.each {
        session.createSQLQuery("drop table if exists $it").executeUpdate()
    }
}

我明白了,

Error occurred running Bootstrap destroy method: No Session found for current thread

org.hibernate.HibernateException: No Session found for current thread at org.grails.orm.hibernate.GrailsSessionContext.currentSession(GrailsSessionContext.java:116) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:688) at sun.reflect.GeneratedMethodAccessor492.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1426)

注意:Grails,3.2.8

我使用了一种变通方法;在 init 中移动了那个位,如下所示

def init = {
    String dbCreate = Holders.grailsApplication.config.getProperty('dataSource.dbCreate', String)
    if(dbCreate == 'create-drop') 
        baseSeqService.drop(customTables)
    baseSeqService.create(customTables)    
    ...
}