sql片段:
有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
<sql id="if-title-author"><if test="title != null">title = #{title}</if><if test="author != null">and author = #{author}</if>
</sql>
引用SQL片段:
<select id="queryBlogIf" parameterType="map" resultType="blog">select * from blog<where><!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace --><include refid="if-title-author"></include><!-- 在这里还可以引用其他的 sql 片段 --></where>
</select>
Foreach
编写接口
List<Blog> queryBlogForeach(Map map);
编写SQL语句
<select id="queryBlogForeach" parameterType="map" resultType="blog">select * from blog<where><!--collection:指定输入对象中的集合属性item:每次遍历生成的对象open:开始遍历时的拼接字符串close:结束时拼接的字符串separator:遍历对象之间需要拼接的字符串select * from blog where 1=1 and (id=1 or id=2 or id=3)--><foreach collection="ids" item="id" open="and (" close=")" separator="or">id=#{id}</foreach></where>
</select>
测试
@Test
public void testQueryBlogForeach(){SqlSession session = MybatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap map = new HashMap();List<Integer> ids = new ArrayList<Integer>();ids.add(1);ids.add(2);ids.add(3);map.put("ids",ids);List<Blog> blogs = mapper.queryBlogForeach(map);System.out.println(blogs);session.close();
}