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>
測試結果: