我正在使用spring-security并添加了一个额外的域 - “UserSettings”,我不想在创建用户时创建它。
为了遵循所有原则,我决定在这里建立一对一的关系。
用户域:
package com.trading.security
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
import com.trading.portal.UserSettings
@EqualsAndHashCode(includes='username')
@ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable {
private static final long serialVersionUID = 1
transient springSecurityService
String username
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
Set<Role> getAuthorities() {
UserRole.findAllByUser(this)*.role
}
def beforeInsert() {
encodePassword()
us = new UserSettings(user:this,currency:'SEK', volumeUnit: 'AM3').save(failOnError:true)
}
def afterInsert() {
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
UserSettings getUserSettings() {
us
}
protected void encodePassword() {
password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}
static transients = ['springSecurityService']
static constraints = {
password blank: false, password: true
username blank: false, unique: true
us unique:true, nullable:true
}
static mapping = {
password column: '`password`'
table '`user`'
}
static hasOne = [us:UserSettings]
}
和UserSettings域:
package com.trading.portal
import com.trading.security.User
class UserSettings {
int id
int SupplierId
String supplierName
String currency
String volumeUnit
static belongsTo = [user : User]
static mapping = {
id column: 'id', type: 'integer'
}
static constraints = {
user()
supplierName()
currency(inList: ['SEK', 'EUR', 'USD', 'GBP'])
volumeUnit(inList: ['AM3', 'PKG', 'AM1', 'AM2'])
supplierId nullable:true
currency nullable:true
volumeUnit nullable:true
supplierName nullable:true
}
}
所以我尝试在插入过程之前在用户域中创建用户设置但是失败并显示消息:
org.springframework.dao.InvalidDataAccessApiUsageException:
Not-null property references a transient value - transient instance must be saved before current operation :
com.trading.portal.UserSettings.user -> com.trading.security.User;
nested exception is org.hibernate.TransientPropertyValueException:
Not-null property references a transient value - transient instance must be saved before current operation :
com.trading.portal.UserSettings.user -> com.trading.security.User
我做错了什么?我该怎么做才能解决这个问题?
答案 0 :(得分:1)
UserSettings
属于User
,因此您必须首先保存用户,并在保存用户之前调用User
对象beforeInsert
。