动态 SQL 是 MyBatis 的强大特性之一
基本标签:
select查询
update修改
delete删除
insert修改
1、if和where
因为采用了Mapper代理开发,我们可以通过写xml的形式来编写我们的SQL,在原有的Mapper文件里我们进行如下改造,
<select id="findUserByIdOrUsername" resultType="com.axiba.domain.User" parameterType="com.axiba.domain.User"> select * from user where 1=1 <if test="id!=0"> and id=#{id} </if> <if test="username!=null and username!=''"> and username like '%${username}%' </if> <if test="gender!=null and gender!=''"> and gender=#{gender} </if> <if test="age!=0"> and age=#{age} </if> </select>
得sql语句可以实现的功能更加多样化,以适应平时业务中的各种情况
2.foreach
foreach 标签主要用于构建 in 条件,可在 sql 中对集合进行迭代.也常用到批量删除、添加等操作中
<select id="findUserByIds" resultType="com.axiba.domain.User" parameterType="com.axiba.domain.QueryUserListId"> select * from user <where> <if test="ids!=null"> <foreach collection="id" item="ids" open="id IN (" close=")" separator=","> #{ids} </foreach> </if> </where> </select>