hibernate - 在应用程序关闭时删除没有后备域类的表

标签 hibernate spring-boot grails gorm

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

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

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)    
    ...
}

关于hibernate - 在应用程序关闭时删除没有后备域类的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57473427/

相关文章:

grails - 如何使 Spock Helper 方法在所有规范或全局范围内可用

json - 使用grails-json-rest-api-plugin时获取请求失败

java - 不一致的数据类型 : expected NUMBER got BINARY

java - RabbitMQ java 客户端停止消费消息

java - Spring Boot 3使用Mock JWT身份验证 token WithMockUser进行安全测试

java - 由于运行 build.gradle 文件而无法启动运行

rest - Grails(未保存)==来自动态查找器的null

java - JPQL,获取具有子列表的对象列表,避免n+1请求并仅选择特定字段

java - 如何使用 Hibernate 级联子删除?

HibernatePersistence 类未发现 JPA + Hibernate + OSGI 的异常