1) 领域模型
让您的代码保持简单。不要创建通用数据模型。这是下地狱的方式。当您将 personToPerson 和 personToStore 分开时,遵循您的代码会容易得多。
实际上建议的解决方案可以同时访问作为合并列表和独立列表的关系。
对于这个问题,我会使用inheritance feature in GORM。
您的课程如下所示:
class Person {
String name
static hasMany = [personToPerson:PersonToPerson,
personToProduct:PersonToProduct,
personToStore:PersonToStore]
static mappedBy = [personToPerson:"from"]
}
class Product{
String productName
}
class Relationship{
String note
}
class Store{
String storeName
}
class PersonToPerson extends Relationship{
Person from
Person to
String relation
static constraints = {
relation(inList:["Friend to", "Enemy of", "Likes", "Hates"])
}
static belongsTo = [ from:Person ]
}
class PersonToProduct extends Relationship{
Person person
Product product
String relation
static constraints = {
relation(inList:["likes", "dislikes"])
}
static belongsTo = [ person:Person ]
}
class PersonToStore extends Relationship{
Person person
Store store
String relation
static constraints = {
relation(inList:["Stock person", "Owner", "Manager", "Patron"])
}
static belongsTo = [ person:Person ]
}
人员、产品和商店的数据库模式是常见的。但是对于关系域看起来像这样:
关系
Field Type Null Default
id bigint(20) No
version bigint(20) No
note varchar(255) No
class varchar(255) No
person_id bigint(20) Yes NULL
product_id bigint(20) Yes NULL
relation varchar(8) Yes NULL
from_id bigint(20) Yes NULL
to_id bigint(20) Yes NULL
store_id bigint(20) Yes NULL
关系域使得访问所有关系域成为可能,只需一个域。
2) 约束
只需将 inList 切换到 validator。比您可以将约束存储在文件或数据库中。
请参阅documentation 或file example。
示例如何在 DB 中存储约束值。首先创建一个域对象。
class Constrain{
String name
String type
}
比领域类看起来:
class PersonToPerson extends Relationship{
Person from
Person to
String relation
static constraints = {
relation(nullable:false, validator:{val, obj ->
def list = Constrain.findAllByType('person').collect{it.name}
return list.contains(val)
})
}
static belongsTo = [ from:Person ]
}