loading

Mybatis - 子查询传递参数

子查询

什么时候用到子查询?

比如,A 实体类下面有一个属性 b,b 的类型是实体类 B,B 下面又有一个一对一的实体类 C。这种多级嵌套关系,就要用到子查询。一层嵌套应该是可以用多表联查直接映射。

对于上面说的情况,inner joinleft join 多表联查可能查询出来的结果不完整或者 null。

但是子查询需要的字段该如何传递?

例子

下面的有两个 association 标签,代表着这个查询有 2 个一对一。通过 column 传递需要的字段给子查询。

格式是 {prop1=col1,prop2=col2},可以传递多个,中间使用逗号隔开,右边 col 是数据库字段名称,左边 prop 是 mybatis 取值符号 #{} 里面的变量名称,又或者对应着实体类的属性名称。符合编程赋值符号,即右边赋值给左边。

<?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="findMap" type="com.bleuon.entity.dto.CollectFlowchart">
        <id column="id" property="id"/>
        <association property="flowchart" javaType="com.bleuon.entity.dto.CollectFlowchart$Flowchart"
                     select="findFlowchartById" column="{flowchartId=flowchart_id}"/>
        <association property="user" javaType="com.bleuon.entity.dto.CollectFlowchart$User" select="findUserById"
                     column="{belongUid=belong_uid}"/>
    </resultMap>
    <select id="findAll" resultMap="findMap" 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 = #{flowchartId}
    </select>

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

</mapper>

其他

使用子查询有个好处就是可以复用 select 查询,在用的时候组装起来就行了。

posted @ 2023-10-03 21:44  Himmelbleu  阅读(50)  评论(0编辑  收藏  举报