How to have multiple One-to-One relationships between three domain classes

醉酒当歌 提交于 2019-12-13 07:18:48

问题


As a follow up question to this, I want to have a User domain class which has an optional one-to-one relationship with BasicProfile domain class, User being the owner which may or may not have a profile. I have this part figured out. What I also want is an optional one-to-one relationship between the AcademicProfile domain class and the User, AcademicProfile being the owner, such that an AcademicProfile may or may not have a User. When I try to replicate this the way I did the first one-to-one relationship, it does not work. Here are my classes.

class User {

    String username
    String password
    String email
    AcademicProfile academicProfile
    Date dateCreated
    Date lastUpdated

    static hasOne = [basicProfile: BasicProfile]

    static constraints = {
        username size: 3..20, unique: true, nullable: false, validator: { _username ->
            _username.toLowerCase() == _username
        }
        password size: 6..100, nullable: false, validator: { _password, user ->
            _password != user.username
        }
        email email: true, blank: false
        basicProfile nullable: true
    }
}

class BasicProfile extends Profile {

    User user
    Date dateCreated
    Date lastUpdated

}

class AcademicProfile extends Profile {

    String dblpId
    String scholarId
    String website
    Date dateCreated
    Date lastUpdated

    static hasOne = [user: User]
    static hasMany = [publications: Publication]

    static constraints = {
        dblpId nullable: true
        scholarId nullable: true
        website nullable: true, url: true
        publications nullable: true
        user nullable: true
    }
}

class Profile {
    String firstName
    String middleName
    String lastName
    byte[] photo
    String bio

    static constraints = {
        firstName blank: false
        middleName nullable: true
        lastName blank: false
        photo nullable: true, maxSize: 2 * 1024**2
        bio nullable: true, maxSize: 500
    }

    static mapping = {
        tablePerSubclass true
    }
}

When I run it, I get the error: Field error in object 'org.academic.User' on field 'academicProfile': rejected value [null];. I don't understand what I am doing wrong.


回答1:


You'll have to add nullable:true constraint for AcademicProfile academicProfile in User class as you mentioned that you need an 'optional' relationship between AcademicProfile & User.

The error itself is self explanatory though, that you can't create a User class's instance, without providing the academicProfile property a non-null value.



来源:https://stackoverflow.com/questions/26512671/how-to-have-multiple-one-to-one-relationships-between-three-domain-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!