Mybatis中List传值
Mybatis遇到List传值时常用方法。
1. List<E>
,E为基本数据类型和String
Mapper类文件:
List<User> selectByIds(List<String> userList);
Mapper.xml文件:
<select id="selectByIds" parameterType="java.lang.String" resultType="com.example.demo.dto.User">
SELECT id,name,note from USER where id in
<foreach collection="list" separator="," open="(" close=")" item="id">
#{id}
</foreach>
</select>
测试结果:
2. List<E>
,E为Object对象
**2.1 不配合@param使用**
Mapper类文件:
List<User> selectUser1(List<User> userList);
Mapper.xml文件:
<select id="selectUser1" parameterType="java.util.List" resultType="com.example.demo.dto.User">
SELECT id,name,note from USER where id in
<foreach collection="list" separator="," open="(" close=")" item="user">
#{user.id}
</foreach>
</select>
测试结果:
**2.2 配合@param使用,自定义参数名**
Mapper类文件:
List<User> selectUser2(@Param("userList") List<User> userList);
Mapper.xml文件:
<select id="selectUser2" parameterType="java.util.List" resultType="com.example.demo.dto.User">
SELECT id,name,note from USER
where id in
<foreach collection="userList" separator="," open="(" close=")" item="user">
#{user.id}
</foreach>
</select>
测试结果:
3. Map<k,V>
,V为List对象
**3.1 不配合@param使用**
Mapper类文件:
List<User> selectByMap1(Map<String,List<User>> paramMap);
Mapper.xml文件:
<select id="selectByMap1" parameterType="java.util.Map" resultType="com.example.demo.dto.User">
SELECT id,name,note from USER
where id in
<foreach collection="userMap" separator="," open="(" close=")" item="user">
#{user.id}
</foreach>
</select>
测试结果:
**3.2 配合@param使用,自定义参数名**
Mapper类文件:
List<User> selectByMap2(@Param("mapList") Map<String,List<User>> paramMap);
Mapper.xml文件:
<select id="selectByMap2" parameterType="java.util.Map" resultType="com.example.demo.dto.User">
SELECT id,name,note from USER
where id in
<foreach collection="mapList.userMap" separator="," open="(" close=")" item="user">
#{user.id}
</foreach>
</select>
测试结果: