【发布时间】:2011-08-06 08:44:45
【问题描述】:
Grails 有very good support 用于将请求参数绑定到域对象及其关联。这在很大程度上依赖于检测以.id 结尾的请求参数并自动从数据库中加载这些参数。
但是,不清楚如何填充命令对象的关联。举个例子:
class ProductCommand {
String name
Collection<AttributeTypeCommand> attributeTypes
ProductTypeCommand productType
}
此对象与ProductTypeCommand 具有单端关联,与AttributeTypeCommand 具有多端关联。所有属性类型和产品类型的列表可从此接口的实现中获得
interface ProductAdminService {
Collection<AttributeTypeCommand> listAttributeTypes();
Collection<ProductTypeCommand> getProductTypes();
}
我使用此界面来填充 GSP 中的产品和属性类型选择列表。我还将这个接口依赖注入到命令对象中,并用它来“模拟”命令对象上的attributeTypes 和productType 属性
class ProductCommand {
ProductAdminService productAdminService
String name
List<Integer> attributeTypeIds = []
Integer productTypeId
void setProductType(ProductTypeCommand productType) {
this.productTypeId = productType.id
}
ProductTypeCommand getProductType() {
productAdminService.productTypes.find {it.id == productTypeId}
}
Collection<AttributeTypeCommand> getAttributeTypes() {
attributeTypeIds.collect {id ->
productAdminService.getAttributeType(id)
}
}
void setAttributeTypes(Collection<AttributeTypeCommand> attributeTypes) {
this.attributeTypeIds = attributeTypes.collect {it.id}
}
}
实际发生的情况是attributeTypeIds 和productTypeId 属性绑定到相关的请求参数和getter/setter “模拟”productType 和attributeTypes 属性。有没有更简单的方法来填充命令对象的关联?
【问题讨论】:
-
我不能回答你的问题,但我个人认为这是一个很好的插件材料,甚至是未来 Grails 版本中的一个功能。
标签: data-binding grails groovy command-objects