繁体   English   中英

GORM多对一映射表

[英]GORM Many-to-one with mapping table

我有几个具有多对一关系的mysql表,正在使用该关系的映射表。 如下

book_type_map
Column         Datatype
book_id        Char(36)
book_type_id   Char(36)

book_type
Column         Datatype
book_type_id   Char(36)
book_type      Text
default        TinyInt(1)

books
Column         Datatype
book_id        Char(36)

如您所见, book表或book_type表没有book_type引用的列,我需要能够从book访问book_type 这些是我的BookBookType域对象

class Book {
    String id
    BookType bookType

    static mapping = {
        table 'books'
        id column: 'book_id', generator: 'uuid2'
        bookType joinTable: [ name: 'book_type_map',
                key: 'book_id',
                column: 'book_type_id']
    }
}

class BookType {
    String id 
    String type
    Boolean default

    static mapping = {
        table 'book_type'
        id column: 'book_type_id', generator: 'uuid2'
        type column: 'book_type'
    }
}

当我运行它时,当我执行Book.findAll()时遇到此异常

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:“字段列表”中的未知列“ this_.book_type_id”

我认为我的映射不正确。 如果有人能指出正确的方向,我将不胜感激。

通常,拥有联接表仅对一对多或多对多关系有意义。 在此示例中,Book只能具有一个BookType,那么为什么需要一个联接表? 您将只有一列具有BookTypeId的列。

我认为您正在寻找的是:

class Book {
    String id

    static hasMany = [bookType: BookType]

    static mapping = {
        table 'books'
        id column: 'book_id', generator: 'uuid2'
        bookType joinTable: [ name: 'book_type_map',
                key: 'book_id',
                column: 'book_type_id']
    }
}

请参阅文档以获取更多详细信息

编辑

如果您设置在此表结构上,则可以翻转关系(不支持此关系)。 这种结构对我来说真的没有意义,但是可以工作:

class Book {
    String id

    static mapping = {
        table 'books'
        id column: 'book_id', generator: 'uuid2'
    }
}

class BookType {
    String id 
    String type
    Boolean default

    static hasMany = [books: Book]    

    static mapping = {
        table 'book_type'
        id column: 'book_type_id', generator: 'uuid2'
        type column: 'book_type'
        books joinTable: [ name: 'book_type_map',
                key: 'book_type_id',
                column: 'book_id']
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM