【问题标题】:"No transaction is in progress" error while following Grails Spring Security Core tutorial遵循 Grails Spring Security Core 教程时出现“没有正在进行的事务”错误
【发布时间】:2020-07-11 17:19:02
【问题描述】:

我正在关注 Grails Spring Security Core 教程 in their documentation。当我到达 24.1.5.5 时,问题就开始了。我被指示将 Bootstrap.groovy 修改为以下内容,然后运行该应用程序:

package com.mycompany.myapp

class BootStrap {

   def init = {

         def adminRole = new Role(authority: 'ROLE_ADMIN').save()

         def testUser = new User(username: 'me', password: 'password').save()

         UserRole.create testUser, adminRole

         UserRole.withSession {
            it.flush()
            it.clear()
         }

         assert User.count() == 1
         assert Role.count() == 1
         assert UserRole.count() == 1

   }
}

运行应用程序给我这个错误:

2020-03-31 15:46:19.294 错误 --- [restartedMain] os.boot.SpringApplication : 应用程序运行失败

javax.persistence.TransactionRequiredException: 没有事务在 进步 在 org.hibernate.internal.SessionImpl.checkTransactionNeeded(SessionImpl .java:3586)

我尝试使用@Transactional 来解决这个问题,但它对错误没有影响。将 Bootstrap.groovy 恢复为其默认值允许应用程序正常运行。本教程缺少什么(或不正确)导致它失败?

【问题讨论】:

    标签: java spring grails spring-security


    【解决方案1】:

    您也可以尝试https://github.com/grails/grails-core/issues/11376 中的解决方案,其中说您可以将配置添加到 application.yml

    hibernate:
        allow_update_outside_transaction: true
    

    【讨论】:

    • 这不是最好的解决方案,但它有效
    【解决方案2】:

    文档已过期。 Hibernate 5.2+ 现在需要事务来进行写操作。添加@Transactional 不起作用,因为init 是一个闭包,并且注释适用于方法或类。

    在引导程序中创建一个新方法并为其添加事务性方法。然后从你的 init 闭包中调用它。例如。

    class BootStrap {
    
        def init = {
            addTestUsers()
        }
    
        @Transactional
        void addTestUsers() {
            def adminRole = new Role(authority: 'ROLE_ADMIN').save()
    
            def testUser = new User(username: 'me', password: 'password').save()
    
            UserRole.create testUser, adminRole
    
            UserRole.withSession {
               it.flush()
               it.clear()
            }
    
            assert User.count() == 1
            assert Role.count() == 1
            assert UserRole.count() == 1
        } 
    }
    

    【讨论】:

    猜你喜欢
    • 2015-06-18
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2013-09-30
    • 2011-09-03
    • 2020-04-05
    相关资源
    最近更新 更多