动态SQL可以省略很多拼接SQL的步骤,使用类似于JSTL方式。
方式1 :
<select id="queryBlogIf" resultType="blog" parameterType="map">select * from mybatis.blog where 1 = 1<if test="title!=null">and title like #{title}</if></select>
public void test02(){SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);Map<String,String> map = new HashMap<>();map.put("title","%ring%");List<Blog> blogs = mapper.queryBlogIf(map);for (Blog blog : blogs) {System.out.println(blog);}sqlSession.close();}
但是这种方式不好的一点就是得手动添加‘%’通配符。
方式2:
<select id="queryBlogIf" resultType="blog" parameterType="map">select * from mybatis.blog where 1 = 1<if test="title!=null">and title like '%${title}%'</if></select>
#{}在字符串中不能够被识别,而${}在字符串中是可以被识别出来的,但是${}是不可以防止sql注入的。
方式3:
利用SQL函数,concat
<select id="queryBlogIf" resultType="blog" parameterType="map">select * from mybatis.blog where 1 = 1<if test="title!=null">and title like concat('%',#{title},'%')</if></select>
建议最好使用第三种方式,最为方便、安全。