我有以下类。 在src/groovy
,
class Profile {
String firstName
String middleName
String lastName
byte[] photo
String bio
}
域类BasicProfile
和AcademicProfile
延长Profile
。
class BasicProfile extends Profile {
User user
Date dateCreated
Date lastUpdated
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
}
}
class AcademicProfile extends Profile {
User user
String dblpId
String scholarId
String website
Date dateCreated
Date lastUpdated
static hasMany = [publications: Publication]
static constraints = {
importFrom BasicProfile
dblpId nullable: true
scholarId nullable: true
website nullable: true, url: true
publications nullable: true
}
static mapping = {
tablePerSubclass true
}
}
然后有一个Publication
的类。
class Publication {
String dblpId
String scholarId
String title
String description
Date publicationDate
int citations
Date dateCreated
Date lastUpdated
static belongsTo = [AcademicProfile]
static hasOne = [publisher: Publisher]
static hasMany = [academicProfiles: AcademicProfile]
static constraints = {
dblpId nullable: true
scholarId nullable: true
title blank: false, maxSize: 100
description nullable: true, maxSize: 500
publicationDate: nullable: true
academicProfiles nullable: false
}
}
最后,我有一个User
类。
class User {
String username
String password
String email
Date dateCreated
Date lastUpdated
static hasOne = [basicProfile: BasicProfile, academicProfile: AcademicProfile]
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
academicProfile nullable: true
}
}
我的问题如下。
- 我想要的关系,其中每个
User
可以任选地具有一个Profile
(无论BasicProfile
或AcademicProfile
)。 我想static hasOne = [profile: Profile]
但我得到的错误说Profile
不同意hasOne
关系。 所以,当前的设置我有一种变通方法。 难道就没有办法,用户可以有一个Profile
是它BasicProfile
或AcademicProfile
? - 其次,在当前的设置,我得到的错误:
Invocation of init method failed; nested exception is org.hibernate.MappingException: An association from the table academic_profile_publications refers to an unmapped class: org.academic.AcademicProfile
Invocation of init method failed; nested exception is org.hibernate.MappingException: An association from the table academic_profile_publications refers to an unmapped class: org.academic.AcademicProfile
当我尝试运行它。 谷歌搜索告诉我,这是与自其他类继承类的问题。 因此从技术上讲,如果我没有hasMany
的关系Publication
与AcademicProfile
,它应该没有任何问题。 但我不希望出现这种情况。 由于发布有许多作者 (AcademicProfile
在我的情况下)和一个作者可能有很多出版物。 那么,有没有办法解决这个问题?