GORM mappedBy 和 mapping 的区别
GORM mappedBy and mapping difference
在 GORM 中,mappedBy
和 mapping
有什么区别?
static mapping = {
...
}
static mappedBy = {
...
}
映射
mapping
只是告诉 GORM 将一个或多个域属性显式映射到特定的数据库列。
class Person {
String firstName
static mapping = {
table 'people'
id column: 'person_id'
firstName column: 'First_Name'
}
}
例如,在这种情况下,我指示 GORM 将 id 属性映射到 people
table 和 firstName
[=45= 的列 person_id
] 到同一 table 的 First_Name
列。
mappedBy
mappedBy
相反,您可以控制 类 关联的单向性或双向性。来自 Grails documentation:
class Airport {
static mappedBy = [outgoingFlights: 'departureAirport',
incomingFlights: 'destinationAirport']
static hasMany = [outgoingFlights: Route,
incomingFlights: Route]
}
class Route {
Airport departureAirport
Airport destinationAirport
}
Airport
定义了两个双向一对多关联。如果你不指定 mappedBy
你会得到一个错误,因为 GORM 无法推断出关联另一端的两个属性中的哪一个(departureAirport
或 destinationAirport
) - 许多应该与相关联。
换句话说,它可以帮助您消除来自双向关联的歧义。
在 GORM 中,mappedBy
和 mapping
有什么区别?
static mapping = {
...
}
static mappedBy = {
...
}
映射
mapping
只是告诉 GORM 将一个或多个域属性显式映射到特定的数据库列。
class Person {
String firstName
static mapping = {
table 'people'
id column: 'person_id'
firstName column: 'First_Name'
}
}
例如,在这种情况下,我指示 GORM 将 id 属性映射到 people
table 和 firstName
[=45= 的列 person_id
] 到同一 table 的 First_Name
列。
mappedBy
mappedBy
相反,您可以控制 类 关联的单向性或双向性。来自 Grails documentation:
class Airport {
static mappedBy = [outgoingFlights: 'departureAirport',
incomingFlights: 'destinationAirport']
static hasMany = [outgoingFlights: Route,
incomingFlights: Route]
}
class Route {
Airport departureAirport
Airport destinationAirport
}
Airport
定义了两个双向一对多关联。如果你不指定 mappedBy
你会得到一个错误,因为 GORM 无法推断出关联另一端的两个属性中的哪一个(departureAirport
或 destinationAirport
) - 许多应该与相关联。
换句话说,它可以帮助您消除来自双向关联的歧义。