【问题标题】:What is the use of unique=true for bidirectional one-to-many with join tableunique=true 用于连接表的双向一对多有什么用
【发布时间】:2023-03-31 15:55:02
【问题描述】:

根据hibernate documentation

section: 8.5.1. one-to-many / many-to-one:

映射文件为:

<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>
    <set name="addresses" 
        table="PersonAddress">
        <key column="personId"/>
        <many-to-many column="addressId"
            unique="true"
            class="Address"/>
    </set>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
    <join table="PersonAddress" 
        inverse="true" 
        optional="true">
        <key column="addressId"/>
        <many-to-one name="person"
            column="personId"
            not-null="true"/>
    </join>
</class>

这里对于多对多有unique="true",但休眠仍然没有在数据库级别创建任何唯一约束。

Hibernate 生成的 DDL 有:

Hibernate: create table ADDRESS (addressId number(10,0) not null, primary key (addressId))
Hibernate: create table PERSON (personId number(10,0) not null, primary key (personId))
Hibernate: create table PersonAddress (addressId number(10,0) not null, personId number(10,0) not null, primary key (personId, addressId))
Hibernate: alter table PersonAddress add constraint FK_g7rqpos3mwhjs6ipfxn6myn3w foreign key (addressId) references ADDRESS
Hibernate: alter table PersonAddress add constraint FK_m5y6eriigdoy1olr7k28a9h6u foreign key (personId) references PERSON

如果 Hibernate 没有创建任何唯一约束,那么为什么我们需要在映射文件中提及它呢?谁能解释一下,谢谢。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    我认为您需要改用 key 元素的 unique 属性:

    <class name="Person">
        <id name="id" column="personId">
            <generator class="native"/>
        </id>
        <set name="addresses" 
            table="PersonAddress">
            <key column="personId" unique="true"/>
            <many-to-many column="addressId"                
                class="Address"/>
        </set>
    </class>
    

    【讨论】:

    • 感谢弗拉德,但根据我的理解,Person 和 Address 之间的关系是多对一的,因此如我的问题中所述,为 addressId 添加唯一性是正确的。我只是关注文档中的内容,但是当休眠生成 DDL 命令时,我没有看到任何唯一约束。
    • 您可以在 addressId 而不是 personId 上添加唯一约束。如果问题是多对多的独特之处,那么我也无法从 Hibernate 代码中找出答案。
    猜你喜欢
    • 2012-03-10
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2010-11-01
    • 2011-09-10
    相关资源
    最近更新 更多