gpt4 book ai didi

java - Hibernate 中稍微复杂的 ManyToMany 关系

转载 作者:行者123 更新时间:2023-12-01 15:15:12 25 4
gpt4 key购买 nike

我的数据库中有以下表格:表:实体表:国家连接表:country_entities

这是实体和国家/地区之间的多对多关系,我在 Entity.hbm.xml 中对此进行了定义,如下所示:

<set name="country" table="countries_entities" cascade="all">
<key column="entity_id" />
<many-to-many column="country_id" class="pikefin.hibernate.Country" />
</set>

以下是连接表country_entities的结构:

screenshot

default_country 字段用于在实体与多个国家/地区关联时指定默认国家/地区。我的问题是,我在 hibernate 状态下表示这一点的适当方式是什么?我认为强力方法是使用 CountryEntity.hbm.xml 配置文件创建一个全新的映射,但我认为通过某种方式扩展现有的多对多关系可能有一种更优雅的方法。

最佳答案

我发现,当您需要其他字段时,创建一个辅助类来表示关联会很有帮助:

@Embeddable
public class CountryAssociation {
...
private Country country;

...
private boolean defaultCountry;
}

然后使用@ElementCollection:

 @ElementCollection
@CollectionTable(name = "country_entities", joinColumns = @JoinColumn(name = "entity_id"))
private Set<CountryAssociation> countries;

我还会删除关联中的 id 字段,因为这种类型的映射实际上并不需要它。

我的 XML 映射有点生疏,但您也可以在 xml 中表示此映射。

我相信 xml 会是这样的:

<set name="countries" table="country_entities">
<key column="entity_id" />
<composite-element class="CountryAssociation">
<property name="country" />
<property name="defaultCountry" />
</composite-element>
</set>

关于java - Hibernate 中稍微复杂的 ManyToMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11715047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com