作为this的后续问题,我想要一个User
域类,该域与BasicProfile
域类User
具有可选的一对一关系{{1}作为拥有者,可能有也可能没有个人资料。我有这个部分想通了。我还想要的是AcademicProfile
域类与作为所有者的User
AcademicProfile
之间的可选一对一关系,以便AcademicProfile
可以或可以没有User
。当我尝试按照我第一次一对一关系的方式复制时,它不起作用。这是我的课程。
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
}
}
当我运行它时,我收到错误:Field error in object 'org.academic.User' on field 'academicProfile': rejected value [null];
。我不明白我做错了什么。
答案 0 :(得分:0)
您必须在User类中为nullable:true
添加AcademicProfile academicProfile
约束,因为您提到您需要在AcademicProfile&amp ;;之间建立'可选'关系。用户。
错误本身是不言自明的,你不能创建一个User类的实例,而不为academicProfile属性提供非null值。