数组判空
传过来的数组 object[] ,在mapper中判空时先判断是否为null,再判断数组长度 object.length是否大于0.
<if test=" object !=null and object.length > 0">
你的逻辑sql
</if>
集合判空
比如参数为List集合,在mybatis中先判断是否为null,不为null再判断集合的长度 object.size() 是否大于0即可。
<if test=" object != null and object.size() > 0">
你的逻辑sql
</if>
不为空循环 使用forech
foreach
如果collection的类型为List
List<UserList> getUserInfo(@Param("userName") List<String> userName);
使用@Param注解自定义keyName;
<if test="userName!= null and userName.size() >0">
USERNAME IN
<foreach collection="userName" item="value" separator="," open="(" close=")">
#{value}
</foreach>
</if>
也可以使用默认属性值list作为keyname
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
如果collection的属性为array
List<UserList> getUserInfo(@Param("userName") String[] userName);
使用@Param注解自定义keyName;
<select id="getUserInfo" resultType="com.test.UserList">
SELECT
*
FROM user_info
where
<if test="userName!= null and userName.length >0">
USERNAME IN
<foreach collection="userName" item="value" separator="," open="(" close=")">
#{value}
</foreach>
</if>
</select>
也可以,使用默认属性值array作为keyname
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
如果collection的属性为Map
List<UserList> getUserInfo(@Param("user") Map<String,String> user);
第一种:获取Map的键值对
多字段组合条件情况下,一定要注意书写格式:括号()
eg: SELECT * FROM user_info WHERE (USERNAME,AGE) IN (('张三','26'),('李四','58'),('王五','27'),......);
<select id="getUserInfo" resultType="com.test.UserList">
SELECT
*
FROM user_info
where
<if test="user!= null and user.size() >0">
(USERNAME,AGE) IN
<foreach collection="user.entrySet()" item="value" index="key" separator="," open="(" close=")">
(#{key},#{value})
</foreach>
</if>
</select>
第二种:参数Map类型,只需要获取key值或者value值
key:
<select id="getUserInfo" resultType="com.test.UserList">
SELECT
*
FROM user_info
where
<if test="user!= null and user.size() >0">
(USERNAME) IN
<foreach collection="user.keys" item="key" separator="," open="(" close=")">
#{key}
</foreach>
</if>
</select>
value:
<select id="getUserInfo" resultType="com.test.UserList">
SELECT
*
FROM user_info
where
<if test="user!= null and user.size() >0">
(USERNAME) IN
<foreach collection="user.values" item="value" separator="," open="(" close=")">
#{key}
</foreach>
</if>
</select>