---
title: "grails hasMany 使用"
author: "小于Brick"
date: "2016-10-14T17:32:41Z"
tags: ["一对多"]
categories: ["编程语言"]
slug: "grails-hasmany"
draft: false
lastmod: "2016-10-17T16:47:09Z"
id: 2330690
url: "https://youngbrick.iteye.com/blog/2330690"
---

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 = {
    }
}
```

 

数据库：

![](http://dl.iteye.com/upload/picture/pic/136255/3b7ee566-ea5f-358e-b169-d15f9c0a9abb.jpg)

 

页面视图：

 

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>
```

![](http://dl.iteye.com/upload/picture/pic/136259/a37764b5-7152-3c22-a9a9-86bc89b87aa3.jpg)

 

 

 

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

 

 

```
也可以通过代码自己控制关系：
@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 ;
}
```