错误信息:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.builder.BuilderException: The expression 'stuMap' evaluated to a null value.
### Cause: org.apache.ibatis.builder.BuilderException: The expression 'stuMap' evaluated to a null value.
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
at com.sun.proxy.$Proxy0.findStudentList3(Unknown Source)
at demo.cyj.Test.main(Test.java:57)
测试类main方法中的部分代码:
//使用<foreach>传入map集合
Student s4_1 = new Student(8,"",0,0);
Student s4_2 = new Student(9,"",0,0);
Student s4_3 = new Student(10,"",0,0);
Student s4_4 = new Student(11,"",0,0);
Map<String,Student> stuMap = new HashMap<>();
stuMap.put("asd", s4_1);
stuMap.put("qwd", s4_2);
stuMap.put("awd", s4_3);
stuMap.put("ads", s4_4);
List<Student> list3 = sd.findStudentList3(stuMap);
System.out.println("用foreach传map值做查询:"+list3);
mapper中的部分代码:
<!-- foreach实现in查询 -->
<select id="findStudentList3" parameterType="map" resultMap="age">
select * from student where id in
<foreach collection="stuMap" index="ind" item="ite" open="(" separator="," close=")">
#{ite.id}
</foreach>
</select>
<resultMap id="age" type="Student">
<result column="stu_age" property="age" />
</resultMap>
原因:
在collection配置里只能解析List或者Array数组,而我传入的是一个map,找不到index,当然不能遍历。
导致我误解能传map,是因为之前网上看到过一句“<foreach>可以遍历Array,List和Map中的值…”。
解决:
将要传递的id都存到一个List中,将List存到要传参的map中,并给List一个键名,在collection中就配置这个键名,然后<foreach>就能成功解析遍历了。
修改后的代码:
测试类main方法中的部分代码:
//使用<foreach>传入map集合,其中map中的值为对象做查询
Map<String,Object> stuMap = new HashMap<>();
List<Integer> stuList = new ArrayList<>();
stuList.add(8);
stuList.add(9);
stuList.add(10);
stuList.add(11);
stuMap.put("stuList", stuList);
List<Student> list3 = sd.findStudentList3(stuMap);
System.out.println("用foreach传map值做查询:"+list3);
修改后的mapper代码:
<!-- foreach实现in查询 -->
<select id="findStudentList3" parameterType="map" resultMap="age">
select * from student where id in
<foreach collection="stuList" index="ind" item="ite" open="(" separator="," close=")">
#{ite}
</foreach>
</select>
<resultMap id="age" type="Student">
<result column="stu_age" property="age" />
</resultMap>
在网上搜索了很久,才终于找到了问题所在,具体是参考的这篇文章:《MyBatis学习总结》by 平凡希-博客园










网友评论