圣杯 2.2.0
我正在尝试创建一个自定义约束来强制用户只有一封主电子邮件。这是导致错误的简化代码:
用户域类
class User {
static hasMany = [emails: Email]
static constraints = {
}
}
电子邮件域类
class Email {
static belongsTo = [user: User]
String emailAddress
Boolean isMaster
static constraints = {
emailAddress unique: ['user']
isMaster validator: { val, obj ->
return !val || Email.findByUserAndIsMaster(obj.user, true) == null
}
}
}
集成测试
class EmailTests {
@Before
void setUp() {
}
@After
void tearDown() {
// Tear down logic here
}
@Test
void testSomething() {
def john = (new User(login: 'johnDoe')).save(failOnError: true, flush: true)
assert (new Email(emailAddress: 'john@gmail.com', user: john, isMaster: true)).save(failOnError: true)
}
}
运行“grails test-app -integration”会导致:
| 失败:testSomething(webapp.EmailTests)
| org.hibernate.AssertionFailure: org.grails.datastore.gorm.GormStaticApi$_methodMissing_closure2.doCall(GormStaticApi.groovy:105) 的 webapp.Email 条目中的空 id(发生异常后不刷新会话)webapp.Email $__clinit__closure1_closure2.doCall(Email.groovy:13) at org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener.onApplicationEvent(AbstractPersistenceEventListener.java:46) at webapp.EmailTests.testSomething(EmailTests.groovy:21)
如果我将唯一约束更改为自定义约束之后,则不会发生问题。这里发生了什么?我想了解这里的任何相关约束的顺序如何?
需要明确的是,这不会导致问题:
static constraints = {
isMaster validator: { val, obj ->
return !val || Email.findByUserAndIsMaster(obj.user, true) == null
}
emailAddress unique: ['user']
}