我有两个域类:
class Person {
String lastname
String firstname
String alias
Date birthday
String notes
static belongsTo = [addressBook: AddressBook, mainAddress: Address]
static hasMany = [tags: Tag, addresses: Address]
static constraints = {
mainAddress nullable: true
addresses nullable: true
alias nullable: true
birthday: nullable: true
tags nullable: true
notes nullable: true
}
}
和
class Address {
AddressType addressType
static belongsTo = [person: Person]
String company
String street
String zipCode
String city
String eMail
String phone
String mobile
String website
static constraints = {
person nullable: true
company nullable: true
website nullable: true
}
}
每个人都有多个地址,可以将一个地址定义为主地址。
在我的控制器里面我做了一个
params.max = Math.min(max ?: 10, 100)
respond Person.list(params)
加载所有地址的所有人。我收到的person-objects包含一个包含所有地址和mainAddress的地址列表。但是,用作主地址的地址在两个对象(列表中的一个和mainAddress对象)中只有空(空)字段。当我没有设置mainAddress时,address-list中的address-object会自动设置所有字段。数据库字段(我到目前为止使用in-memory-db)似乎是正确的:
create table address (id bigint generated by default as identity, version bigint not null, address_type varchar(255) not null, city varchar(255) not null, company varchar(255), e_mail varchar(255) not null, mobile varchar(255) not null, person_id bigint, phone varchar(255) not null, street varchar(255) not null, website varchar(255), zip_code varchar(255) not null, primary key (id))
create table person (id bigint generated by default as identity, version bigint not null, address_book_id bigint not null, alias varchar(255), birthday timestamp not null, firstname varchar(255) not null, lastname varchar(255) not null, main_address_id bigint, notes varchar(255), primary key (id))
有没有人知道,为什么我的地图不起作用?
感谢您的提前帮助
罗兰
答案 0 :(得分:1)
您的模型存在许多问题,最严重的是person-mainAddress关系没有所有者,即每一方belongsTo
另一方。如果可能的话,我会将你的模型简化为
class Person {
// non-address properties omitted, because they're not relevant to this question
static hasMany = [addresses: Address]
Address getMainAddress() {
Address.createCriteria().get {
eq 'person', this
eq 'isMain', true
}
}
static transients = ['mainAddress']
static constraints = {
addresses nullable: true, validator: { addresses ->
// this prevents a person from having more than one main address
addresses?.count { it.isMain } <= 1
}
}
}
class Address {
// non-person properties omitted, because they're not relevant to this question
boolean isMain = false
static belongsTo = [person: Person]
static constraints = {
// is it really OK for an address not to be associated with a person?
person nullable: true
}
}
我认为这符合您的要求,但是更简单的模型,因为Person
和Address
答案 1 :(得分:1)
我现在找到了解决方案:
class Person {
Address mainAddress
static hasMany = [addresses: Address]
static constraints = {
addresses nullable: true
mainAddress nullable: true, unique: true
}
static mapping = {
addresses joinTable: [name: 'person_address',key: 'person_id', column: 'address_id']
mainAddress lazy: false
}
}
class Address {
}
这样,地址映射到连接表person_address,而mainAddress通过地址表中的main_address_id映射。需要“mainAddress:lazy”映射,因为否则不会填充mainAddress的字段。