动态sql
foreach:
@Data public class Blog { private String id; private String title; private String author; private Date createTime; private int views; }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.nbg.dao.BlogMapper">
<!--collection:用于参数传递,可以是数组或者list,set等集合-->
<!--open/close:配置的是用什么元素将循环变量包围起来-->
<!--separator:循环变量的分隔符-->
<!--index:当前元素在集合位置的下标,即:集合的索引,vs的下标从0开始-->
<!--item:循环中的变量-->
<select id="getBlogByForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="vs" open="views in (" close=")" separator="," item="v">
#{v}
</foreach>
</where>
</select>
</mapper>
@Test public void getBlogByForeach() { BlogMapper mapper = session.getMapper(BlogMapper.class); HashMap map = new HashMap(); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); map.put("vs",list); for (Blog blogByForeach : mapper.getBlogByForeach(map)) { System.out.println(blogByForeach); } session.close(); }