使用带有默认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)
}
}
在控制器中,我使用以下代码保存用户:
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)
}
}
随后我又重新生成了视图和控制器。现在,当我尝试从控制器保存用户对象时,使用:
userInstance.save(flush: true)
我收到以下异常:
类:org.hibernate.AssertionFailure 消息:login.User条目中的null id(发生异常后不刷新会话)
任何帮助将不胜感激。
信息:如果我从新的/修改过的类中删除了大小约束 保存很好。
答案 0 :(得分:-1)
我使用Grails 3.1.12遇到了同样的问题。这就是我发现的以及我是如何解决它的。
问题:
您正在尝试将大小约束放入将要加入的字段中。这意味着像“admin5”这样的密码将在域生命周期结束时作为编码的pwd转向。例如,db将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,我建议您在创建域实例之前在服务或控制器层上进行验证。