我有 6 个这样结构的表(底部有一个更具描述性的示例):
A
每一项都与 B 中的一项和 C 中的一项相关。
aid | bid | cid
B
每个项目都与 D 中的多个项目相关。
bid
C
每个项目都与 D 中的多个项目相关。
cid
D
每个项目都与 B 和 C 中的多个项目相关。
did
E
将 B 中的项目映射到 D 中的项目。
bid | did
F
将 C 中的项目映射到 D 中的项目。
cid | did
现在我正在尝试在MyBatis中编写一个映射器来映射表A中的项目。该映射器与表B和C的映射器有关联,并且表B和C的映射器都有一个包含项目的集合表 D 的内容。
将 B 或 C 单独映射到表 D 的项目不是问题,因为使用 E 或 F 的简单联接操作就足够了。 然而,当尝试从表 A 的角度映射所有内容时,问题就出现了。 由于表 A 与表 B 和表 C 都关联,并且它们都与表 D 关联,所以我不知道如何让 B 和 C 的映射器区分表 D 中适合它们的项目。
基本上,我试图从 A 的映射器的角度将 D 连接到 B 和 C。
有没有办法在 MyBatis 中连接表 D 两次,同时保持两次连接之间的区别,以便 B 和 C 的映射器可以区分两者?
感谢您的帮助!
编辑
这是一个带有更具描述性名称的小示例。
房子
houseid | livingroomid | kitchenid
1 | 1 | 1
客厅
livingroomid
1
厨房
kitchenid
1
家具
furnitureid | furniturename
1 | couch
2 | lamp
3 | fridge
客厅家具
livingroomid | furnitureid
1 | 1
1 | 2
厨房家具
kitchenid | furnitureid
1 | 2
1 | 3
我当前的映射器:
Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper>
<resultMap type="com.project.models.house.House" id="HouseResult">
<id property="id" column="houseid" />
<association property="livingroom" resultMap="LivingRoomResult" />
<association property="kitchen" resultMap="KitchenResult" />
</resultMap>
<resultMap type="com.project.models.livingroom.LivingRoom" id="LivingRoomResult">
<id property="id" column="livingroomid" />
<collection property="furniture" resultMap="FurnitureResult" />
</resultMap>
<resultMap type="com.project.models.kitchen.Kitchen" id="KitchenResult">
<id property="id" column="kitchenid" />
<collection property="furniture" resultMap="FurnitureResult" />
</resultMap>
<resultMap type="com.project.models.furniture.Furniture" id="FurnitureResult">
<id property="id" column="furnitureid" />
<result property="name" column="furniturename" />
</resultMap>
<select id="getAllHouses" resultMap="HouseResult">
SELECT
houses.houseid,
houses.livingroomid,
houses.kitchenid
FROM houses
-- Get the living room
INNER JOIN livingrooms ON livingrooms.livingroomid = houses.livingroomid
-- Get the kitchen
INNER JOIN kitchens ON kitchens.kitchenid = kitchens.kitchenid
-- Here somehow join the furniture for both the living room and the kitchen?
</select>
</mapper>
最佳答案
实际上,您必须将 D 连接到表 B,并相应地为表 C 别名。
假设表 d 的 bd 已连接到 B 和 cd。
现在,如果您希望两个别名表(bd 和 cd)的表 d 具有相同的结果映射,您可以执行以下操作:
select bd.did as bd_did, cd.did as cd_did
如果您还没有遇到过结果映射的 column_prefix
属性,这就是您的结果映射的外观
<collection type="D" resultMap="d" column_prefix="bd_" />
关于java - MyBatis 中不同关联中两次映射同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45689875/