Mybatis动态sql:

if标签

<if test="(id)!=null and (id!='')">
   
AND id =  #{id}
</if>
<
if test="(user.balance)!=null and(user.balance!='')">
    
AND balance = #{user.balance}
</if>

Test中此写的是表达式,ognl取值+sql语句的写法

这样写出现一个问题,if标签中的and关键字没法放,前后都可能出错。

while标签

能够自动删除if标签中的前and

如果后面的条件都不成立,where关键字也可以省略。

foreach标签
1.如果传入对象:

<!--对象-->
<select id="findUserByObj" parameterType="cn.hd.pojo.QueryVo"resultType="cn.hd.pojo.User">
   
<include refid="selectUser"></include>
   
<where> id in
       
<foreach collection="ids" item="id"separator="," open="(" close=")">
           
#{id}
        </foreach>
   
</where>
</
select>

如果使用对象的话,collection中的值必须是实体类中的属性名,item中的id是自己定义的一个名字,理解为是该集合中的一个子元素,

2.如果传入数组:

<!--数组-->
<select id="findUserByArray" parameterType="java.util.Arrays" resultType="cn.hd.pojo.User">
   
<include refid="selectUser"></include>
   
<where> id in
       
<foreach collection="array" item="id" separator=","open="(" close=")">
           
#{id}
        </foreach>
   
</where>
</
select>

 

3.如果传入集合

<select id="findUserByList" parameterType="java.util.ArrayList"resultType="cn.hd.pojo.User">
   
<include refid="selectUser"></include>
   
<where> id in
   
<foreach collection="list" item="id" separator=","open="(" close=")">
     
  #{id}
    </foreach>
   
</where>
</
select>

 

 

Sql片段:

首先要将公共的sql语句提取出来

<sql id="selectUser">
     SELECT * FROM user
</sql>

<select id="findUserById" parameterType="cn.hd.pojo.QueryVo"resultType="cn.hd.pojo.User">
  
 <includerefid="selectUser"></include>将上面的sql语句引入进来
   
<where>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值