sql片段:
- 把sql语句的公共片段提取出来,提高sql的重用性。
- 最好是基于单表的,不要存在where标签。
使用:
- 使用 把之前的查询语句中的相同部分抽取出来。
<sql id="if-name-author">
<if test="name!=null">
and name=#{name}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
- 在需要使用的地方用 引入
<include refid="if-name-author"></include>
测试是否可用:
@org.junit.Test
public void testIf(){
SqlSession sqlSession=MyBatisUtils.getSqlSession();
BookMapper bookMapper=sqlSession.getMapper(BookMapper.class);
HashMap map=new HashMap();
map.put("name","三国");
map.put("author","娃哈");
List<Book> bookList= bookMapper.queryBookByIf(map);
for (Book book : bookList) {
System.out.println(book);
}
sqlSession.close();
}