簡體   English   中英

Grails / Gorm-將域對象與自身1:M相關聯

[英]Grails/Gorm - relating a domain object to itself 1:M

我有一個遺留數據庫,用於在grails 2.2.1應用程序中映射域對象。

我正在使用的表將FK關系返回給它的孩子。 幸運的是,我知道我只需要深入層次結構中的一個層次即可。

T_FOO
----------------------
I                 LONG
CHILD_FOO         LONG

這是可能的結果集:

I  CHILD_FOO
-  ---------
1  NULL
2  NULL
3  1
4  1
5  2

我的域對象如下所示:

class Foo {
    long instanceId
    static hasMany = [childFoos: Foo]

    static mapping {
        table 'T_FOO'
        id generator: 'assigned', name: 'instanceId', column: 'I', type: 'long'
        version false
        autoTimestamp false
        instanceId column: 'I'

        // I tried joining the table to itself and it didn't work
        childFoos joinTable [name: 'T_FOO', key: 'CHILD_FOO', column: 'I'
    }
}

查詢不起作用。 Hibernate將t0.class放到選擇列表中,然后失敗。

有什么建議嗎?

問候,羅賓

這很麻煩,但是我最終通過創建另一個包含對原始類的引用的域類來解決了該問題。 我想找到一種更好的方法,但是現在可以使用。

我正在測試的數據庫表:

mysql> desc t_foo;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| I           | bigint(20)  | NO   | PRI | NULL    |       |
| Description | varchar(45) | YES  |     | NULL    |       |
| I_CHILDFOO  | bigint(20)  | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+

mysql> select * from t_foo;
+---+--------------+------------+
| I | Description  | I_CHILDFOO |
+---+--------------+------------+
| 1 | Parent 1     |       NULL |
| 2 | Parent 2     |       NULL |
| 3 | Child 1 of 1 |          1 |
| 4 | Child 1 of 1 |          1 |
| 5 | Child 1 of 2 |          2 |
+---+--------------+------------+

我的課程如下所示:

package db.legacy

class Foo {

    long instanceId
    String info

    static hasMany = [ kids: ChildFoo ]

    static constraints = {
    }

    static mapping = {
        table 'T_FOO'
        id generator: 'assigned', name: 'instanceId', column: 'I', type: 'long'
        version false
        autoTimestamp false
        instanceId column: 'I'
        info column: 'Description'
        kids column: 'I_CHILDFOO'
    }
}

class ChildFoo {

    long instanceId
    Foo parentFoo

    static mapping = {
        table 'T_FOO'
        id generator: 'assigned', name: 'instanceId', column: 'I', type: 'long'
        version false
        autoTimestamp false
        instanceId column: 'I'
        parentFoo column: 'I_CHILDFOO'
    }
}

當我進行以下測試時,它會很好地工作:

def foo = db.legacy.Foo.get(1)
foo.kids.each { bar -> 
    assert bar.parentFoo.instanceId == foo.instanceId
}

看起來像是這樣草率/ hacky的解決方案。 如果有人有任何想法或想法,我希望能聽到。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM