如何使用链接表映射Hibernate中的多对多列表 [英] How to map many-to-many List in Hibernate with a Link Table

查看:84
本文介绍了如何使用链接表映射Hibernate中的多对多列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用链接表在Hibernate中映射多对多。例如,我有两个类:Parent和Child类:

I would like to map a many-to-many in Hibernate using a link table. I have two classes, Parent and Child class, for example:

public class Parent{

private List<Child> _children;

//...getters and setters
}

我使用链接表(link_table),它包含三列 link_id parent_id child_id 。数据库是SQL服务器,id类型是uniqueidentifier。所以,我通常使用guid作为id字段。

I use a link table (link_table) with three columns link_id, parent_id, and child_id. The database is SQL server and id types are uniqueidentifier. So, I usually use guid for the id fields.

如何使用 < list /> 标记,如果这是使用正确的标记?你知道任何好的文档来完成这个吗?

How can you implement this using the <list /> tag if this is the correct tag to use? Do you know of any good documentation to accomplish this?

我目前得到一个ConstraintViolationException,但一直没能找到任何好的文档或例子。

I am currently getting a ConstraintViolationException but have not been able to find any good documentation or examples of this.

我认为一个主要问题是:如何指定链接表中自动生成的 link_id

I think a main issue is: how to specify the link_id to be automatically generated in the link table.

推荐答案

我不认为有可能(或必须)将link_id主键添加到联接表。连接表通常由两个参与表的主键组成。

I don't think that it is possible (or necessary) to add a link_id primary key to the join table. The join table will usually consist of the primary keys of the two participating tables.

使用XML你需要这样的语法:

Using XML you will need syntax like this:

 <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>

尽管我发现使用注释更好。

Although I find annotations better to use.

这篇关于如何使用链接表映射Hibernate中的多对多列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆