簡體   English   中英

Hibernate:以一對多關系指定列

[英]Hibernate: Specifying columns in a one-to-many relationship

我正在嘗試為數據庫模式構建一個Hibernate層,我基本上無法控制。 簡化后,有兩個表。

parent有兩個重要的列:

  • parent_id ,整數,主鍵,自動增量
  • parent_code ,string,unique key,由某個黑盒子生成(讓我們說這是一個UUID,為了理智)
  • 再加上一堆數據列

child有兩個重要的列:

  • child_parent_id ,整數,主鍵,自動增量
  • child_parent_code ,string,指向父級parent_code值的外鍵
  • 再加上一堆數據列

我希望能夠調用Parent.getChilds()並獲取Child對象的集合。 但是設置Hibernate映射文件似乎是不可能的。 它使用下面的映射做的是使用parent_id值(而不是parent_code )搜索child表。

Parent.hbm.xml

    <set name="childs" inverse="true" lazy="true" table="child" fetch="select">
        <key>
            <column name="child_parent_code" not-null="true" />
        </key>
        <one-to-many class="foo.bar.Child" />
    </set>

Child.hbm.xml

    <many-to-one name="parent" class="foo.bar.Parent" fetch="select">
        <column name="child_parent_code" not-null="true" />
    </many-to-one>

我花了一個小時仔細閱讀我的Java Persistence with Hibernate副本,但我無法弄清楚如何做我想做的事情。 可能嗎?

我會考慮使用hibernate注釋。 我發現它們更容易使用xml定義。

這是注釋格式的代碼:

@Entity
@Table(name="parent")
public class Parent
{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @ManyToOne
        @JoinColumn(name="child", referencedColumnName = "id")
    private Child child;
}

@Entity
@Table(name = "child")
public class Child
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;

    @Column(name = "code")
    public String code;
}

在父母中嘗試這樣的事情:

<set name="childs" inverse="true" lazy="true" table="child" fetch="select">
    <key column="child_parent_code" property-ref="code" />
    <one-to-many class="foo.bar.Child" />
</set>

這在孩子身上:

<many-to-one name="parent" class="foo.bar.Parent"
    fetch="select" column="child_parent_code" property-ref="code" />

我假設父代碼中的代碼屬性稱為“代碼”。

暫無
暫無

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

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