gpt4 book ai didi

java - myBatis 多对多关系

转载 作者:行者123 更新时间:2023-12-02 11:21:21 26 4
gpt4 key购买 nike

关于我之前有关 MyBatis 中映射的问题,我现在在进行多对多关系时遇到问题

我有以下对象

由于隐私问题,我无法发布实际的对象定义和 XML

class ObjectA {
List<Items> items;
List<Products> products;

//getters setters
}

class Items {
int id;
String description;
List<Tags> tags;
}

class Tags {
int id;
int item_id;
String tag;
}

SQL 涉及将 Items 表与 Tags 表连接ON Tags.ITEM_ID = Items.ID

基本上,它返回行并将它们映射到此 MyBatis

<resultMap id="getObjectA" type="ObjectA">
<collection property="items" javaType="ArrayList" ofType="Items" resultMap="getItems"/>

...

</resultMap>

<resultMap="getItems" type="Items">
<id property="id" column="ITEMS.id"/>
<result property="description" column="ITEMS.description"/>
<collection property="tags" javaType="ArrayList" ofType="Tags" resultMap="getTags"/>
</resultMap>

<resultMap id="getTags" type="Tags">
<id property="id" column="TAGS.id"/>
<result property="item_id" column="TAGS.item_id"/>
<result property="tag" column="TAGS.tag"/>
</resultMap>

从技术上讲,该设置有效并返回一个 ObjectA,其中包含一个项目列表,每个项目都包含一个标签列表。当每个项目仅存在一个标签时,映射很好,但当一个项目包含多个标签时,它会创建多个具有相同 ID 的项目,每个项目都包含一个仅包含查询结果中的一个标签的列表。

最佳答案

父对象创建重复意味着mybatis无法正确识别对象,即<id property="id" column="ITEMS.id"/>不按预期工作。基本上id需要 element 以便 mybatis 知道结果集中多行中重复的父记录引用同一个对象。

一个可行的选择是确保不同表中的列具有唯一的名称,并在结果映射中使用该唯一的名称。

对于您的示例映射器应如下所示:

<resultMap type="ObjectA" id="objectaMap">
<id column="id" property="id"/>
<collection property="items" javaType="ArrayList" ofType="Items" columnPrefix="ITEM_">
<id column="id" property="id"/>
<result property="description" column="description"/>
<collection property="tags" javaType="ArrayList" ofType="Tags" columnPrefix="TAG_">
<id column="id" property="id"/>
<result property="tag" column="tag"/>
</collection>
</collection>
</resultMap>

<select id="getObjects" resultMap="objectaMap">
select o.*, i.id as ITEM_ID, i.description as ITEM_DESCRIPTION, t.id as ITEM_TAG_ID, t.tag as ITEM_TAG_TAG
from objecta o
join items i on (i.object_id = o.id)
join tags t on (t.item_id = i.id)
</select>

注意 items 中的所有列如何表有ITEM_前缀和 tags 相同表。

关于java - myBatis 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896691/

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