0

我有一个无法更改的旧数据库,并且我有这个设置

class Foo {

    static hasMany = [bars:Bar]

    static mapping = {
    version false

    columns {
        id column: "FooId"
        color column: "FooColor"

        bars joinTable: [name: "FooBar", key: 'FooId', column: 'BarId']
    }

    transient
    def getBarName(){
       ((Bar)this.bars.toArray()[0]).name
    }
 }

class Bar {

    static hasMany = [foos:Foo]

    static belongsTo = [Foo, Baz]

    static mapping = {
    version false

    columns {
        id column: "BarId"
        name column: "BarName"
    }
 }

当我尝试访问控制器中的方法 getBarName() 时,Hibernate 会将反列名称转换为“bar_id”。是否有某种方法可以设置像 id 和 property 列的映射?

顺便说一句。如何正确实现 getBarName()?这不可能是正确的实现......

*编辑*
----------------------------------------------------------- ------------------------------------
显然我上面不清楚。问题是我已经有一个连接列,其形式为

-------------------
|RowId|FooId|BarId|
-------------------
|  1  | abc | 123 |
-------------------

Benoit 的答案在这种情况下并不适用,因为我想避免为 joinTable 提供域对象。

*编辑 2 *
---------------------------------------------- ------------------------
解决了。虽然不明白...但是在两个域类之间拆分连接表信息并且它可以工作...

class Foo {

    static hasMany = [bars:Bar]

    static mapping = {
    version false

    columns {
        id column: "FooId"
        color column: "FooColor"

        bars joinTable: [name: "FooBar", key: 'FooId']
    }

    transient
    def getBarName(){
       ((Bar)this.bars.toArray()[0]).name
    }
 }

class Bar {

static hasMany = [foos:Foo]

    static belongsTo = [Foo, Baz]

    static mapping = {
    version false

    columns {
        id column: "BarId"
        name column: "BarName"

        bars joinTable: [name: "FooBar", key: 'BarId']
    }
 }
4

1 回答 1

0

如文档多对一/一对一映射和一对多映射中所述:

使用双向一对多,您可以根据上一节中关于一对一关联的示例,通过更改关联多方的列名来更改所使用的外键列。但是,对于单向关联,需要在关联本身上指定外键。

你给出的例子是:

class Person {
String firstName
static hasMany = [addresses: Address]
static mapping = {
        table 'people'
        firstName column: 'First_Name'
        addresses column: 'Person_Address_Id'
    }
}
于 2012-12-06T17:45:47.590 回答