gpt4 book ai didi

grails - 为什么 grails.gorm.autoFlush 设置为 true 不起作用?

转载 作者:行者123 更新时间:2023-12-02 03:46:31 24 4
gpt4 key购买 nike

考虑以下代码:

class User {
static constraints = {
email email: true, unique: true
token nullable: true
}

String email
String password
String token
}
<小时/>
@TestFor(User)
@TestMixin(DomainClassUnitTestMixin)
class UserSpec extends Specification {
def "email should be unique"() {
when: "twice same email"
def user = new User(email: "test@test.com", password: "test")
def user2 = new User(email: "test@test.com", password: "test")

then: "saving should fail"
user.save()
!user2.save(failOnError: false)
}
}

使用以下配置(部分),application.yml:

grails:
gorm:
failOnError: true
autoFlush: true

为什么user2.save(failOnError: false)由于没有保存到数据库而没有返回false

运行输出:grails test-app *UserSpec:

businesssoftware.UserSpec > email should be unique FAILED org.spockframework.runtime.ConditionNotSatisfiedError at UserSpec.groovy:40

当我用 user.save(flush: true) 替换 user.save() 时,它确实工作。

但是 https://grails.github.io/grails-doc/latest/guide/conf.html 的文档,第 4.1.3 节声称:

grails.gorm.autoFlush - If set to true, causes the merge, save and delete methods to flush the session, replacing the need to explicitly flush using save(flush: true).

作为引用,这是 grails --version 的输出:

| Grails Version: 3.0.2
| Groovy Version: 2.4.3
| JVM Version: 1.8.0_40

这正是我正在做的事情,我在这里错过了什么?

最佳答案

我认为 autoFlush 文档具有误导性。

grails.gorm.autoFlush - If set to true, causes the merge, save and delete methods to flush the session, replacing the need to explicitly flush using save(flush: true).

看一下 GormInstanceApi 的 save() 方法和 doSave() 。在 doSave() 结束时,您将看到仅当刷新参数为 true 时才会刷新 session :

if (params?.flush) {
session.flush()
}

代码中没有任何内容表明刷新参数可以来自传递给 save() 的参数之外的任何其他位置。

我找不到代码来证明这一点,但我认为 autoFlush 在 Hibernate session 关闭时发挥作用,例如当 Controller 或服务方法存在/返回时。

此外,用于 Spock 和 JUnit 的 GORM 实现并不是真正的 GORM,因此它甚至可能不使用 autoFlush 配置。

我要在这里冒险了。我还没有尝试过这个,但是您也许能够手动刷新 session 。

@TestFor(User)
@TestMixin(DomainClassUnitTestMixin)
class UserSpec extends Specification {
def "email should be unique"() {
when: "twice same email"
def user = new User(email: "test@test.com", password: "test")
def user2 = new User(email: "test@test.com", password: "test")
simpleDatastore.currentSession.flush()

then: "saving should fail"
user.save()
!user2.save(failOnError: false)
}
}

simpleDataStore 来自DomainClassUnitTestMixin .

关于grails - 为什么 grails.gorm.autoFlush 设置为 true 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com