2

我在提交表单时尝试使用commandObject来验证我的数据。我可以在commandObject. 我的场景是这样的。

两个简单的classes有很多关系:

class Book{
    String nameBook
}

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

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

@grails.validation.Validateable
class MyValidateCommand{

    String nameAuthor
    static hasMany = [books:Book]


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

}

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

4

2 回答 2

7

hasMany在 GORM 中用于域对象中的关联。在命令对象的情况下,为每个域拥有不同的命令对象(例如: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.
    }
}
于 2013-08-22T14:03:08.457 回答
0

不知道你为什么不试试喜欢(正常的休眠 hasMany 声明)

class MyValidateCommand{

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


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

}
于 2014-03-21T05:22:00.430 回答