Back

Mybatis之XML篇

Mybatis xml映射文件中,除了常见的select、insert、updae、delete标签之外 还有动态sql标签 trim、 where、set、foreach、if、choose、when、otherwise、bind等

where标签

反例:

SELECT
module_code, oper_type, oper_content, data_id, oper_by, oper_name, oper_dt, INET_NTOA(oper_ip) as oper_ip
FROM tb_operation_log l WHERE 1=1
<if test="param.moduleCode != null">
    AND l.module_code = #{param.moduleCode}
</if>
<if test="param.operBy != null and param.operBy !=''">
    AND l.oper_by = #{param.operBy}
</if>
<if test="param.operName != null and param.operName !=''">
    AND l.oper_name LIKE CONCAT("%",#{param.operName},"%")
</if>
<if test="param.operDtStart != null and param.operDtEnd != null">
    AND l.oper_dt BETWEEN #{param.operDtStart} AND #{param.operDtEnd}
</if>
order by l.oper_dt desc

正例:

SELECT
module_code, oper_type, oper_content, data_id, oper_by, oper_name, oper_dt, INET_NTOA(oper_ip) as oper_ip
FROM tb_operation_log l
<where>
    <if test="param.moduleCode != null">
        AND l.module_code = #{param.moduleCode}
    </if>
    <if test="param.operBy != null and param.operBy !=''">
        AND l.oper_by = #{param.operBy}
    </if>
    <if test="param.operName != null and param.operName !=''">
        AND l.oper_name LIKE CONCAT("%",#{param.operName},"%")
    </if>
    <if test="param.operDtStart != null and param.operDtEnd != null">
        AND l.oper_dt BETWEEN #{param.operDtStart} AND #{param.operDtEnd}
    </if>
</where>
order by l.oper_dt desc

foreach标签

参数未加@Param命名,默认是list

select p.* from tb_process_btn_param p where p.param_type = 0 and p.btn_id in
<foreach collection="list" item="btnId" index="index" open="(" close=")" separator=",">
    #{btnId}
</foreach>
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus