mybatis学习笔记4-动态SQL

mybatis支持在mapper中配置动态sql,根据传入参数确定sql语句中的where条件。个人认为框架支持动态sql是挺好的。不过如果编程之前能预知sql使用情况的,多写几个静态sql对于系统性能还是有好处的,毕竟动态sql还是需要做一次代码解析的。

mybatis的动态sql具体的机制包括:
1. if:普通的条件判断,比较适合在一个固定条件的前提下叠加动态条件。例如:

<select id="findUser3" resultMap="usermap">
select
a.id as user_id,
a.name as user_name,
a.sex as user_sex,
a.age as user_age
from T_User a where a.age=20
<if test="name!=null">
AND a.name=#{name}
</if>
</select>

2. choose,when,otherwise:类似switch,满足其中一个when分支或otherwise
3. where,if:单存使用if语句在没有固定where条件的时候,容易造成最终组装出来的sql语法错误。增加where标记可以避免。例如:

<select id="findUser4" resultMap="usermap">
select
a.id as user_id,
a.name as user_name,
a.sex as user_sex,
a.age as user_age
from T_User a
<where>
<if test="name!=null">
a.name=#{name}
</if>
<if test="fname!=null">
AND a.fname=#{fname}
</if>
</where>
</select>

4. foreach.特别适用于使用in条件查询的情况。一开始不知道in里面要放多少个条件,可以使用foreach来接收一个列表,动态生成一个sql。例如:

<select id="findUserByIds" resultMap="usermap">
select
a.id as user_id,
a.name as user_name,
a.sex as user_sex,
a.age as user_age
from T_User a where a.id in
<foreach collection="list" index="index" item="item"
open="(" close=")" separator=",">
#{item}
</foreach>
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值