public List<Student> getMultiStudentInMap(List<Map.Entry<String, String>> params, long percentage) { System.out.println(params); return studentMapper.selectForeachEntry(params, percentage); }
public List<Student> selectForeachEntry(@Param("params") List<Map.Entry<String, String>> params, @Param("percentage") long percentage);
<!-- 在foreach中,傳入參數爲Map或Map.Entry對象時,index是鍵,item是值 --> <select id="selectForeachEntry" resultMap="studentResult"> select * from test_student t where t.percentage = #{percentage} <if test="params.size() > 0"> and ( <foreach item="param" index="index" collection="params" separator=" or "> (t.name = #{index} and t.branch = #{param}) </foreach> ) </if> </select>
List<Map.Entry<String, String>> idList = new ArrayList<>(); Map<String, String> map = new TreeMap<>(); map.put("name_1", "a"); map.put("name_2", "b"); map.put("name_3", "c"); Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { idList.add(it.next()); } List<Student> students = studentDao.getMultiStudentInMap(idList, 0);
==> Preparing: select * from test_student t where t.percentage = ? and ( (t.name = ? and t.branch = ?) or (t.name = ? and t.branch = ?) or (t.name = ? and t.branch = ?) ) ==> Parameters: 0(Long), name_1(String), a(String), name_2(String), b(String), name_3(String), c(String) <== Total: 0
使用Map生成Map.Entry有侷限性,key值不能重複。不使用Map,就須要本身實現Map.Entry接口: class MyEntry implements Map.Entry<String, String> {...}java
public class Pair<K, V> { private K key; private V value; }
public List<Student> getMultiStudentByPairList(List<Pair<String, String>> myentryList, long percentage) { System.out.println(myentryList); return studentMapper.selectByPairList(myentryList, percentage); }
public List<Student> selectByPairList(@Param("pairs") List<Pair<String, String>> pairs, @Param("percentage") long percentage);
<!-- 在foreach中,傳入參數爲List/Set對象時,index是當前迭代的序號,item是當前迭代的元素 --> <select id="selectByPairList" resultMap="studentResult"> select * from test_student t where t.percentage = #{percentage} <if test="pairs.size() > 0"> and ( <foreach item="pair" index="index" collection="pairs" separator=" or "> (t.name = #{pair.key} and t.branch = #{pair.value}) </foreach> ) </if> </select>
List<Pair<String, String>> myentryList = new ArrayList<>(); myentryList.add(new Pair<String, String>("name_1", "a")); myentryList.add(new Pair<String, String>("name_2", "b")); myentryList.add(new Pair<String, String>("name_3", "c")); List<Student> students = studentDao.getMultiStudentByPairList(myentryList, 0);
==> Preparing: select * from test_student t where t.percentage = ? and ( (t.name = ? and t.branch = ?) or (t.name = ? and t.branch = ?) or (t.name = ? and t.branch = ?) ) ==> Parameters: 0(Long), name_1(String), a(String), name_2(String), b(String), name_3(String), c(String) <== Total: 0