grails hasMany 使用

 

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 ;
}
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值