Mybatis动态sql

1.if(多条件动态sql)

<!-- 传递pojo综合查询用户信息 -->
    <select id="findUserList" parameterType="user" resultType="user">
        select * from user 
        where 1=1 
        <if test="id!=null"> //如果id满足条件,就加上该限制条件
        and id=#{id}
        </if>
        <if test="username!=null and username!=''">//同理
        and username like '%${username}%'
        </if>
    </select>

注意要做不等于空字符串校验。

2.Where

上边的sql也可以改为:

 <select id="findUserList" parameterType="user" resultType="user">
        select * from user 
        <where>
        <if test="id!=null and id!=''">
        and id=#{id}
        </if>
        <if test="username!=null and username!=''">
        and username like '%${username}%'
        </if>
        </where>
  </select>
  <where/>可以自动处理第一个and。把多余的and删掉

3.foreach

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

  • 需求
    传入多个id查询用户信息,用下边两个sql实现:
SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)
SELECT * FROM USERS WHERE username LIKE '%张%'  AND  id IN (10,89,16)
  • 在pojo中定义list属性ids存储多个用户id,并添加getter/setter方法
public class QueryVo {
    private User user;
    //自定义用户扩展类
    private UserCustom userCustom;
    //传递多个用户id
    private List<Integer> ids;
}
  • mapper.xml
<if test="ids!=null and ids.size>0">
       <foreach collection="ids"  open=" and id in(" close=")"  item="id"  separator="," >
            #{id}
       </foreach>
</if>

4.Sql片段

Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的,如下:

<!-- 传递pojo综合查询用户信息 -->
    <select id="findUserList"  parameterType="user" resultType="user">
        select * from user 
        <where>
        <if test="id!=null and id!=''">
        and id=#{id}
        </if>
        <if test="username!=null and username!=''">
        and username like '%${username}%'
        </if>
        </where>
    </select>
  • 将where条件抽取出来:
<sql id="query_user_where">
    <if test="id!=null and id!=''">
        and id=#{id}
    </if>
    <if test="username!=null and username!=''">
        and username like '%${username}%'
    </if>
</sql>
  • 使用include引用:
<select id="findUserList"  parameterType="user" resultType="user">
    select * from user 
    <where>
    <include refid="query_user_where"/>
    </where>
</select>

注意:如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,如下:

<include refid="namespace.sql片段”/>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值