MyBatis的各种动态sql写法
文章目录
1、各种动态sql所需使用的标签
1.foreach 标签
首先在mapper中接收到的方法参数应该是list、map或者array类型的。
使用方法如下
<foreach item="item" collection="list" index="index" open="(" separator="," close=")">
#{item}
</foreach>
<!--
# item表示集合中每一个元素进行迭代时的别名.
# index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.
# collection 为传进来的collection参数的 *类型*
# open表示该语句以什么开始
# separator表示在每次进行迭代之间以什么符号作为分隔符
# close表示以什么结束
-->
<!--
如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
如果传入的是单参数且参数类型是一个Array数组的时候,collection属性值为array
-->
2.where标签
<!-- 此处配置了别名,因此参数类型以及返回值类型可以使用简略写法-->
<!--使用where标签时,第一个if标签中的sql语句,可以省略and关键字-->
<select id="findUserByWhere" resultType="user" parameterType="user">
select * from user
<where>
<if test="username != null">
username = #{username}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
</select>
3. sql标签
Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的
使用方法如下
<sql id="userInfoColumnsList">
<trim suffixOverrides=",">
<if test="item.userName != null">userName,</if>
<if test="item.age != null">age,</if>
<if test="item.sex != null">sex,</if>
<if test="item.salary != null">salary,</if>
<if test="item.completed != null">completed,</if>
<if test="item.remark != null">remark</if>
</trim>
</sql>
<sql id="userInfoValuesList">
<trim suffixOverrides=",">
<if test="item.userName != null">#{item.userName},</if>
<if test="item.age != null">#{item.age},</if>
<if test="item.sex != null">#{item.sex},</if>
<if test="item.salary != null">#{item.salary},</if>
<if test="item.completed != null">#{item.completed},</if>
<if test="