Mybatis - 通过中间表查询表A和表B

发布时间 2023-10-03 21:48:35作者: Himmelbleu

中间表

中间表存储了表 A 的 id 和表 B 的 id,除此之外还存储了自身需要的字段,如创建时间、id。

xml

很简单,通过多个子查询获取数据就可以了,将中间表的字段传递给子查询的 column,子查询获取这个参数进行 where 条件查询。

<?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 namespace="com.bleuon.mapper.CollectFlowchartMapper">

    <resultMap id="mapOfFindAll" type="com.bleuon.entity.dto.CollectFlowchart">
        <id column="id" property="id"/>
        <association property="flowchart" javaType="com.bleuon.entity.dto.CollectFlowchart$Flowchart"
                     select="findFlowchartById" column="flowchart_id"/>
        <association property="user" javaType="com.bleuon.entity.dto.CollectFlowchart$User" select="findUserById"
                     column="belong_uid"/>
    </resultMap>
    <select id="findAll" resultMap="mapOfFindAll" resultType="com.bleuon.entity.dto.CollectFlowchart">
        select *
        from co_collect_flowchart
        where collect_uid = #{uid};
    </select>

    <select id="findFlowchartById" resultType="com.bleuon.entity.dto.CollectFlowchart$Flowchart">
        select *
        from t_flowcharts
        where id = #{id}
    </select>

    <select id="findUserById" resultType="com.bleuon.entity.dto.CollectFlowchart$User">
        select id, avatar, username
        from t_users
        where id = #{id};
    </select>

</mapper>