2008-12-22 53 views
5

我想使用鏈接表在Hibernate中映射多對多。我有兩個班,親子班,例如:如何使用鏈接表映射Hibernate中的多對多列表

public class Parent{ 

private List<Child> _children; 

//...getters and setters 
} 

我用三列link_idparent_id,並child_id鏈接表(link_table)。數據庫是SQL服務器,id類型是uniqueidentifier。所以,我通常使用guid作爲id字段。

如果這是使用正確的標籤,您如何使用<list />標籤執行此操作?你知道任何好的文件來完成這個嗎?

我目前得到一個ConstraintViolationException,但一直沒能找到任何好的文檔或這個例子。

我認爲一個主要問題是:如何指定link_id在鏈接表中自動生成。

回答

5

我不認爲這是可能的(或需要)添加link_id主鍵的加入表。連接表通常由兩個參與表的主鍵組成。

使用XML,你需要的語法是這樣的:

<class name="Parent"> 
    .... 
    <list name="children" table="link_table"> 
    <key column="parent_id"/> 
    <many-to-many column="child_id" 
     class="Children"/> 
    </list> 
    ... 
</class> 

<class name="Child"> 
... 
<list name="parents" inverse="true" table="link_table"> 
    <key column="child_id"/> 
    <many-to-many column="parent_id" 
     class="Parent"/> 
</list> 
... 
</class> 

雖然我找到註解更好地使用。

+5

這也需要一個索引列我相信。 – Brandon 2008-12-31 17:10:28

0

我不確定您是否可以輕鬆地將現有數據庫與現有數據關閉。 Hibernate通常更好定義了自己的數據模式的第一次連接...

我只脫下多到許多與註釋,但我覺得Hibernate文檔提供了基於XML的例子:link text

7

我做到這一點使用說明,特別是@ManyToMany和@JoinTable:

Hibernate Docs:

@Entity 
public class Employer implements Serializable { 
    @ManyToMany(
     targetEntity=org.hibernate.test.metadata.manytomany.Employee.class, 
     cascade={CascadeType.PERSIST, CascadeType.MERGE} 
    ) 
    @JoinTable(
     name="EMPLOYER_EMPLOYEE", 
     [email protected](name="EMPER_ID"), 
     [email protected](name="EMPEE_ID") 
    ) 
    public Collection getEmployees() { 
     return employees; 
    } 
} 


@Entity 
public class Employee implements Serializable { 
    @ManyToMany(
     cascade = {CascadeType.PERSIST, CascadeType.MERGE}, 
     mappedBy = "employees", 
     targetEntity = Employer.class 
    ) 
    public Collection getEmployers() { 
     return employers; 
    } 
} 
+0

很好的答案,幫了很多 – 2017-03-28 15:30:15

0

我在網上發現了一個非常好的博客,它提供了2種方法將附加字段添加到多對多映射的hibernate列。 傳統上我們期望多對多的映射給出一個新的表格將FK映射表格。但有辦法調整,並添加更多的字段/列到這個連接表。

這個連接表可能包含PK或可能包含一些沒有PK的額外字段。 查看此博客的具體實施See Here

並根據您的示例,您需要在表中額外的PK,以便您聲明一個新表ParentChildren並聲明您的主鍵爲linkId。我只展示了annoated的parentchildren類,因爲父類和子類中的多對多映射的註釋可以從上面的帖子引用。

@Entity 
@Table(name = "parent_children") 
public class ParentChildren{ 
    @Id @GeneratedValue 
    private long linkId; 

    @ManyToOne(cascade = CascadeType.ALL) 
    @JoinColumn(name = "parent_id") 
    private Parent parent; 

    @ManyToOne(cascade = CascadeType.ALL) 
    @JoinColumn(name = "children_id) 
    private Children children; 

    // additional fields if you want 
    private boolean activated; 

    //getters and setters 
    } 
} 

因此,這將創建已LINKID作爲主鍵和PARENT_ID和children_id爲外鍵映射表。只需清楚你爲什麼要單獨將link_id作爲主鍵以及如何使用它。