900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > mybatis动态sql模糊查询方法

mybatis动态sql模糊查询方法

时间:2023-12-22 14:29:01

相关推荐

mybatis动态sql模糊查询方法

动态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>

建议最好使用第三种方式,最为方便、安全。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。