2017-03-08 54 views
0

我正在使用spring-security並添加了一個額外的域 - 「UserSettings」,我不希望在創建用戶時創建該域。Grails在一對一關係中創建客戶端

要遵循所有原則,我決定在此創建一對一關係。

用戶域:

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 

    } 
} 

所以我試圖創建用戶域前插入過程中usersettings但未能與消息:

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 

我做了什麼錯了?我能做些什麼來解決這個問題?

回答

1

UserSettings屬於User因此您必須先保存用戶並在User對象beforeInsert在用戶保存之前調用。

+0

所以這意味着創建用戶時不可能自動創建UserSettings?我必須這樣做嗎? u =新用戶(...)。save(); u.us =新建UserSetting(...) – larand