Grails对将请求参数绑定到域对象及其关联有很好的支持。这在很大程度上依赖于检测以数据库结尾的请求参数.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
属性。有没有更简单的方法来填充命令对象的关联?