今天想用多条件查询,使用foreach遍历map得到字段名和字段值,百度了许多东西都没有一个能解决的。后来终于解决了,代码如下。
public int searchCount(Map<String, Object> map) {
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("aa", map);
return sqlSessionTemplate.selectOne("org.lanqiao.dao.StudentDao.searchCount", map1);
}
这是我的dao层,根据多条件查询相应的数量
<!-- 符合条件的数据一共有多少条 -->
<select id="searchCount" resultType="int" parameterType="map" >
select count(*) from student
<where>
<foreach collection="aa.keys" index="index" item="item" separator="and">
${item}=#{aa[${item}]}
</foreach>
</where>
</select>
这是我的mapper,多条件查询数量
解释:首先我的dao层的map又进行了一次封装,再用一个map存起来,key值是 aa,这样就可以在mapper.xml 通过 aa 拿到我的map
其次mapper里面的foreach的是 aa.keys (就是该map的所有key值,item是具体的每一项),${item}得到key值,#{aa[${item}]} 拿到value值。
追加:${} 与 #{}是有区别的。前者得到字段名(不会用 '' 包起来,因为数据库的字段值只能是值) ,后者相反