我使用静态脚手架为Test
域类创建CRUD方法。仅使用创建的TestController
时,保存新的Test
对象没有任何问题。但是,我想扩展功能并实现相应的TestService
类。这样做我现在总是在保存Test
对象时出错:Connection is read-only. Queries leading to data modification are not allowed
然后它开始出现故障。遵循TestService
的代码。如果我正确理解,则无需将@Transactional
批注与save
和delete
这两个方法一起使用,因为它们可以直接从类继承该功能。
package test.services
import grails.transaction.Transactional
import test.Test
@Transactional
class TestService {
@Transactional(readOnly = true)
def tests() {
Test.list()
}
@Transactional(readOnly = true)
def count() {
Test.count()
}
@Transactional
def save(test) {
test.save()
}
@Transactional
def delete(test) {
test.delete()
}
}
这也是将
Test
对象保存在TestController
中的代码:def save(Test test) {
if (testInstance == null) {
notFound()
return
}
if (testInstance.hasErrors()) {
respond testInstance.errors, view:'create'
return
}
testService.save(testInstance)
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'test.label', default: 'Test'), testInstance.id])
redirect testInstance
}
'*' { respond testInstance, [status: CREATED] }
}
}
我唯一更改的是声明
testService.save(testInstance)
的行。在此之前,脚手架过程将testInstance.save flush: true
我真的没看错。特别是,使用或多或少相同的配置可以毫无问题地保存另一个域类的对象。
任何帮助,将不胜感激!
最佳答案
首先,请确保您使用的是最新的hibernate或hibernate4插件版本。
当前最新的hibernate插件版本是3.6.10.17,hibernate4插件版本是4.3.5.5。
该问题可能是由Grails 2.3.0中GRAILS-10063添加的只读集成引起的。缺省行为已由GRAILS-11177修复,并已通过此提交https://github.com/grails/grails-data-mapping/commit/6447be90修复。
还要确保您缺少这些设置,或者在Config.groovy中将其设置为false
grails.hibernate.pass.readonly = false
grails.hibernate.osiv.readonly = false
(如果缺少这些设置,则不必添加这些设置)
仅在DataSource.groovy的hibernate配置中将singleSession = false设置与hibernate插件(hibernate3)一起使用只读集成功能才有意义。 Spring的Hibernate 4 OSIVI不支持singleSession = false模式。
关于grails - Grails-@Transactional,连接为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25138324/