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

 

数据库:

grails hasMany 使用_第1张图片

 

页面视图:

 

create.gsp页面添加:


   
grails hasMany 使用_第2张图片

 

 

 

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

 

 

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

    render "ok";
    return ;
}
 

 

 

 

你可能感兴趣的:(grails3,hasMany,一对多)