ITeye博客

grails hasMany 使用

小于Brick · 2016-10-14 17:32 · grails · 编程语言 · 一对多 · Markdown

grails3 hasMany,一对多关系

参考:http://docs.grails.org/latest/ref/Domain%20Classes/hasMany.html

 

对象说明:

作者:Author

书:Book

Author拥有多个Book

数据库会建立3张表:

author、book、 author_book(一_ 多)

 

domain:

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

 

class Book {
    String title
    static constraints = {
    }
}

 

数据库:

 

页面视图:

 

create.gsp页面添加:

<g:form action="save">
   <fieldset class="form">
      <f:all bean="author"/>
<!-- 这里 ↓-->
      <g:select name="books" from="${com.o2o.Book.list()}" size="5" multiple="yes" optionKey="id"
value="${author?.books}" />
<!-- 这里 ↑-->
   </fieldset>
   <fieldset class="buttons">
        <g:submitButton name="create" class="save" value="${message(code: 'default.button.create.
label', default: 'Create')}" />
   </fieldset>
</g:form>

 

 

 

============================================================================

 

 

也可以通过代码自己控制关系:
@Transactional
def saveDemo() {
    def author = new Author();
    author.name = "张三";
    def book2 = new Book(title: "书2");
    def book3 = new Book(title: "书3");
    Set<Book> books=new HashSet<Book>();
    books.add(book2);
    books.add(book3);
    //主要是下面这行代码
    author.addToBooks(books);
    author.errors.each{
        println "it:"+it
    }
    author.save(flush:true);

    render "ok";
    return ;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。