MyBatis中涉及到字符串列表的查询,比如:
SELECT
max(age)
FROM t_users
WHERE
name in ('zhangsan', 'lisi', 'wangermazi')
一种MyBatis XML写法是:(将’zhangsan’, ‘lisi’, ‘wangermazi’ 作为nameList参数传入)
<select id="findMaxBirthday" resultType="java.util.Date" >
SELECT
max(birthday)
FROM t_users
<where>
<if test="nameList != null and nameList != ''">
name in (#{nameList})
</if>
</where>
</select>
这种可能会返回结果数量为Result:1,而结果却为null。
以下写法可以解决:(用到foreach)
<select id="findMaxBirthday" resultType="java.util.Date" >
SELECT
max(birthday)
FROM t_users
<where>
<if test="nameList != null and nameList != ''">
name in
<foreach item="item" index="index" collection="nameList" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</where>
</select>