只是想知道是否有人可以建议域类架构应该如何。我有一个名为Category的域类,但可能存在具有相同域(类别)的子类。例如,设备Toaster可以属于Kitchen,子类别SmallAppliance。
class Category {
static hasMany = [appliances: Appliance, categories: Category]
String name
}
class Appliance {
static belongsTo = Category
static hasMany = [categories: Category]
}
答案 0 :(得分:3)
Appliance域类需要进行一些小调整。猜一下!! :)
我们Appliance
categories
中不需要hasMany关系。这种关系是这样的:
Category --> SubCategory (type of Category) --> Appliance
设备belongsTo
父类别以及subCategory
,而Category
本身就是class Appliance {
static belongsTo = Category
String name
}
class Category {
String name
static hasMany = [appliances: Appliance, subCategories: Category]
}
。因此,在设备中,belongsTo关系就足够了。
使用相反:
//Category
def kitchen = new Category(name: "Kitchen")
kitchen.save()
//Appliance
def toaster = new Appliance(name: "Toaster")
kitchen.addToAppliances(toaster)
kitchen.save()
//Sub Categories
def electrical = new Category(name: "Electrical")
//Electrical category is a sub category of Kitchen
kitchen.addToSubCategories(electrical)
//Toaster is an appliance of Category Kitchen and Sub Category Electrical
electrical.addToAppliances(toaster)
kitchen.save()
assert kitchen
assert toaster
assert electrical
assert kitchen.appliances.size() == 1
kitchen.appliances.each{assert it.name == 'Toaster'}
assert kitchen.subCategories.size() == 1
kitchen.subCategories.each {assert it.name == 'Electrical'}
assert electrical.appliances.size() == 1
electrical.appliances.each {assert it.name == 'Toaster'}
这是一个可以更好地理解事物的测试用例:
{{1}}
让我们知道它是否仍然不清楚。