动态SQL
声明:本文章属于学习笔记,根据狂神说的Mybatis编写
Mybatis在线文档:https://mybatis.org/mybatis-3/zh/index.html
一丶 动态SQL之if语句
首先我们要理解什么是动态的sql语句,假如我只按照摸个sql语句的固定格式,那么他就不是动态的。我们在固有的sql语句中根据不同的值得限定,所查询的不同的值,那么就可以称之为动态的。
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
数据库表:
接口的设计:
BlogMapper.xml文件的配置:
<select id="queryBlog" parameterType="map" resultType="blog">
select *from blog where 1=1
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</select>
在这里我们看后面的where 1=1 其实就是为了确保可以必须查出来结果用的。if中的语句其实就是拼接语句。
测试类测试:
@Test
public void test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<Object, Object> map = new HashMap<>();
map.put("title","kdynb");
List<Blog> blogs = mapper.queryBlog(map);
for (Blog blog : blogs) {
System.out.