gpt4 book ai didi

grails - Grails域类约束修改导致异常

转载 作者:行者123 更新时间:2023-12-02 14:56:17 25 4
gpt4 key购买 nike

我在默认的h2数据库中使用grails 2.0.3,并具有以下用户域类:

class User {
transient springSecurityService

String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired

Preferences preferences
Company company
Personal personal

static constraints = {
username email: true, blank: false, unique: true
password blank: false
preferences unique: true
company unique: true
personal unique: true
}

static mapping = {
password column: '`password`'
}

Set<Role> getAuthorities() {
UserRole.findAllByUser(this).collect { it.role } as Set
}

def beforeInsert() {
encodePassword()
}

def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}

protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}

在 Controller 中,我使用以下代码保存用户:
userInstance.save(flush: true)

现在,今天下午,我意识到密码字段应具有大小限制,因此修改了域类,使其变为如下所示(仅更改了限制):
class User {
transient springSecurityService

String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired

Preferences preferences
Company company
Personal personal

static constraints = {
username email: true, blank: false, unique: true
password blank: false, size: 6..15
preferences unique: true
company unique: true
personal unique: true
}

static mapping = {
password column: '`password`'
}

Set<Role> getAuthorities() {
UserRole.findAllByUser(this).collect { it.role } as Set
}

def beforeInsert() {
encodePassword()
}

def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}

protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}

随后,我再次生成了 View 和 Controller 。现在,当我尝试从 Controller 保存用户对象时,请使用:
userInstance.save(flush: true)

我收到以下异常:

类:org.hibernate.AssertionFailure
消息:登录名中的id为空。用户条目(发生异常后请勿刷新 session )

任何帮助将不胜感激。

Info: If I remove the size constraint from the new/modified class the saving happens fine.

最佳答案

我在使用Grails 3.1.12时遇到了同样的问题。这就是我发现的问题以及解决方法。

问题:

您正在尝试将大小约束放到将要确认的字段上。这意味着像“admin5”这样的密码将在域生命周期的结尾以编码的pwd的形式出现。例如,数据库会将pwd存储为:“$ 2a $ 10 $ dn7MyN.nsU8l05fMkL / rfek / d1odko9H4QUpiNp8USGhqx9g0R6om”。

验证过程会将大小约束应用于未编码的pwd(域生命周期中的验证步骤),由于用户键入的pwd在该范围内,因此验证将通过。但是在save()方法(域生命周期中的持久性步骤)上,pwd将在插入或更新之前进行编码。 enconding方法将创建一个大小大于您的约束的pwd,而Hibernate将使pwd大小的assert()失败。

解:

如果您不必担心maxSize,请使用minSize约束

 static constraints = {
password blank: false, minSize:6
}

如果需要验证maxSize,则建议您在创建域实例之前在Service或Controller层上进行验证。

关于grails - Grails域类约束修改导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14832630/

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