命令对象和hasmany

时间:2013-08-22 13:48:46

标签: grails command-objects

我在提交表单时尝试使用commandObject来验证我的数据。我可以在commandObject中验证hasMany关系吗?我的cenario是这样的。

拖曳简单classes whith有很多关系:

class Book{
    String nameBook
}

class Author{
    String nameAuthor
    static hasMany = [books:Book]    
}

使用hasMany的简单commandObject我想在提交表单时验证。

@grails.validation.Validateable
class MyValidateCommand{

    String nameAuthor
    static hasMany = [books:Book]


    static constraints = {
        nameAuthor nullable:false
        books nullable:false
    }

}

ps:我知道这个commandObject是错误的,它不编译。但我可以做这样的事吗???

2 个答案:

答案 0 :(得分:7)

GORM中的

hasMany用于Domain对象中的关联。对于命令对象,为每个域提供不同的命令对象(例如:AuthorCommandBookCommand)将是一种清晰的方法,命令对象将如下所示:

import org.apache.commons.collections.list.LazyList
import org.apache.commons.collections.functors.InstantiateFactory

//Dont need this annotation if command object 
//is in the same location as the controller
//By default its validateable
@grails.validation.Validateable
class AuthorCommand{
    String nameAuthor
    //static hasMany = [books:Book]

    //Lazily initialized list for BookCommand
    //which will be efficient based on the form submission.
    List<BookCommand> books = 
            LazyList.decorate(new ArrayList(), 
                              new InstantiateFactory(BookCommand.class))

    static constraints = {
        nameAuthor nullable:false
        books nullable:false

        //Let BookCommand do its validation, 
        //although you can have a custom validator to do some 
        //validation here.
    }
}

答案 1 :(得分:0)

不确定为什么不能尝试(正常的hibernate hasMany声明)

class MyValidateCommand{

    String nameAuthor
    Set<Book> books= new HashSet<Book>();


    static constraints = {
        nameAuthor nullable:false
        books nullable:false
    }

}