java - 遵循 Grails Spring Security Core 教程时出现“没有正在进行的事务”错误
问题描述
我正在关注他们文档中的 Grails Spring Security Core 教程。当我到达 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] osboot.SpringApplication:应用程序运行失败
javax.persistence.TransactionRequiredException:在 org.hibernate.internal.SessionImpl.checkTransactionNeeded(SessionImpl .java:3586) 处没有正在进行的事务
我试图使用@Transactional 来解决这个问题,但它对错误没有影响。将 Bootstrap.groovy 恢复为其默认值允许应用程序正常运行。本教程中缺少什么(或不正确)导致它失败?
解决方案
文档已过期。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
}
}
推荐阅读
- php - Google Search Console - 新添加的网站显示在 Google 网站管理员中,但未显示在 Search Console 中
- python - 查找两个时钟指针之间度数的问题(Python)
- javascript - 如何使用 JS 为多个元素创建一个数字计数器?
- java - 将整数数组转换为集合然后查找交点
- html - 即使清除缓存后网站图标也不显示
- python - 索引列表中包含的每个元组的最 Pythonic 方式
- python - 如何在python中删除具有nan值的行
- node.js - Node/Express (Mongo) 传递完成(“完成不是函数”错误)
- python - 如何在 Python 中使用多处理终止进程?
- javascript - 访问 JSON 对象的键值