Grails

Summary

简单的级联关系

  • 一个 Author 会有很多 Book。
  • Author 对 Book 是一对多的关系。
  • Book 对 Author 是多对一的关系。
  • Book belongs to Author。
  • 在 Book 上设置 Foreign Key 对应 author_id,可以单独删除 book,但是存在书不能删除 author。

Demo

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

class Book {
    String title
    static belongsTo = [author: Author]
    static constraints = {
    }
    static mapping = {
        author cascade: 'all'
    }
}

// 自动创建出来的表结构
CREATE TABLE
    author
    (
        id BIGINT NOT NULL,
        version BIGINT NOT NULL,
        name CHARACTER VARYING(255) NOT NULL,
        PRIMARY KEY (id)
    );

CREATE TABLE
    book
    (
        id BIGINT NOT NULL,
        version BIGINT NOT NULL,
        title CHARACTER VARYING(255) NOT NULL,
        author_id BIGINT NOT NULL,
        PRIMARY KEY (id),
        CONSTRAINT fkklnrv3weler2ftkweewlky958 FOREIGN KEY (author_id) REFERENCES "author" ("id")
    );

Reference

http://docs.grails.org/3.1.1/ref/Domain%20Classes/belongsTo.html
http://grails.1312388.n4.nabble.com/How-to-cascade-delete-belongsTo-isn-t-working-td3329469.html

原文地址:https://www.cnblogs.com/duchaoqun/p/12851515.html