动态sql

通过mybatis提供的各种标签方法实现动态拼接sql语句。

常用有<if>、<where>、<foreach>

基于不同需求来进行使用

需求:根据性别和名字查询用户

按原始方法在mapper.xml中写sql语句:

<select>
select * from user where sex = #{sex} and username = #{username}
</select>

但如果在查询时没有给username给值,则可能导致默认username = null 而致使查询 出错。

所以解决方案,是使用动态sql的if标签

<select>
select * from user 
where 
<if test="sex != null and sex != ' ' ">
sex = #{sex} 
</if>
<if test="username != null and username != ' ' ">
and username = #{username}
</if>
</select>

如果没有给username给值,那么语句将变成

select * from user where sex = #{sex}

但这依然存在隐患,如果sex为空,运行是就会语法报错,多了一个and

这时候就引入了where标签

<!-- 根据条件查询用户 -->
<select>
  select * from user
<!-- where标签可以自动添加where,同时处理sql语句中第一个前and关键字 -->
    <where>
        <if test="sex != null">
            AND sex = #{sex}
        </if>
        <if test="username != null and username != ''">
            AND username = #{username}
        </if>
    </where>
</select>

 

Sql片段:

当sql语句部分重复太多时,可以抽取出来放在sql标签中,

<sql id="selector">
      select * from user
</sql>


<!-- 根据条件查询用户 -->
<select>
    <include refid="selector"/>
<!-- where标签可以自动添加where,同时处理sql语句中第一个前and关键字 -->
    <where>
        <if test="sex != null">
            AND sex = #{sex}
        </if>
        <if test="username != null and username != ''">
            AND username = #{username}
        </if>
    </where>
</select>

 

foreach标签

向sql传递数组或List,mybatis使用foreach解析,如下:

根据多个id查询用户信息

查询sql:

SELECT * FROM user WHERE id IN (1,10,24)

在UserMapper.xml添加sql,如下:

<!-- 根据ids查询用户 -->
<select id="queryUserByIds" parameterType="queryVo" resultType="user">
    SELECT * FROM `user`
    <where>
        <!-- foreach标签,进行遍历 -->
        <!-- collection:遍历的集合,这里是QueryVo的ids属性 -->
        <!-- item:遍历的项目,可以随便写,,但是和后面的#{}里面要一致 -->
        <!-- open:在前面添加的sql片段 -->
        <!-- close:在结尾处添加的sql片段 -->
        <!-- separator:指定遍历的元素之间使用的分隔符 -->
        <foreach collection="ids" item="item" open="id IN (" close=")" separator=",">
            #{item}
        </foreach>
    </where>
</select>              

 

posted @ 2018-10-19 14:45  X凯  阅读(1187)  评论(0编辑  收藏  举报