今天想用多条件查询,使用foreach遍历map获得字段名和字段值,百度了许多东西都没有一个能解决的。后来终于解决了,代码以下。html
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); }
<!-- 符合条件的数据一共有多少条 --> <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>
解释:首先个人dao层的map又进行了一次封装,再用一个map存起来,key值是 aa,这样就能够在mapper.xml 经过 aa 拿到个人mapjava
其次mapper里面的foreach的是 aa.keys (就是该map的全部key值,item是具体的每一项),${item}获得key值,#{aa[${item}]} 拿到value值。sql
追加:${} 与 #{}是有区别的。前者获得字段名(不会用 '' 包起来,由于数据库的字段值只能是值) ,后者相反 数据库