动态SQL的元素
1.if
在我们的SQL语句中,查询条件的值如果为空,可能会导致查询结果错误
为了避免这种错误的发生,我们使用了if判断.
<select id="getUserList" resultMap="userList" >
select * from smbms_user where 1=1
<if test="userRole!=null">
and u.userRole=#{userRole}
</if>
<if test="userName!=null and userName!=''">
and u.userName like CONCAT('%',#{userName},'%')
</if>
</select>
2.where
select * from smbms_user
<where>
<if test="userRole!=null">
and u.userRole=#{userRole}
</if>
<if test="userName!=null and userName!=''">
and u.userName like CONCAT('%',#{userName},'%')
</if>
</where>
这里的where写法不推荐大家使用,相比之下,上面if里面写了一个where 1=1 之后再到后面加入if的判断结果出来较为好用
MyBatis入参为数组类型的foreach迭代
<select id="getUserByRoleId_foreach_array" resultMap="userArrayByRole">
select * from smbms_user where userRole in
<foreach collection="array" item="roleIds" open="(" separator="," close=")">
#{roleIds}
</foreach>
</select>
<resultMap type="cn.smbms.pojo.User" id="userArrayByRole">
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
</resultMap>
item:表示集合中每一个元素进行的迭代时的别名
index:指定一个名称,用于标识在迭代过程中,每次迭代到的位置
open:表示该语句以什么开始
separator:表示在每次迭代之间以什么符号作为分隔符
close:表示该语句以什么结束
collection:最关键并最容易出错的属性,
若入参为单参数且参数类型为List的时候,collection属性值为list,
若入参为单参数且参数类型为数组的时候,collection属性值为array,
若入参为多参数,collection属性值为Map,