相较于直接映射,用MyBatis写动态SQL的灵活性更强,结合HashMap, 可以指定需要查询哪几个字段,以及对应的字段的值,从而提供更大的便利。
以写blog为例:
1.指定Mapper接口的方法,传进去的参数是Map<String,Object>类型
List<Blog> queryBlogIf(Map<String,Object> map);
4.在XXXMapper.xml的select 语句中,使用if 元素限定传入的条件
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from BLOG WHERE 1=1
<if test="title!=null">
and title = #{title}
</if>
<if test="author!=null">
and author = #{author}
</if>
</select>
3.在测试类中,定义并赋值对应的键值,实现 mapperd对应的接口方法
Map<String,Object> map=new HashMap<String,Object>(); //HashMap指定要筛选的列,与其对应的值
//put the key(DB column) and value into HashMap
map.put("id",ID);
map.put("title","This is Blog1!");
// map.put("Author","Jamie");
// map.put("create_time",System.currentTimeMillis());
// map.put("views",100);
mapper.queryBlogIf(map);
4.查询结果
DB数据:
MyBatis查询结果: