说起sql语句,大家在jdbc阶段最为头疼的就是那个五个步骤吧。重复,冗余,繁杂。而mybatis的出现便很好的解决了动态sql的问题。我接下来,就为大家来说一下这个动态sql的巧妙之处吧。
动态SQL的相关学习
-
首先还是搭建实体类以及插入需要的测试数据
-
@AllArgsConstructor @NoArgsConstructor @Datapublic class Blog { private int id; private String title; private String author; private Date createTime; private int views; }
IF的学习
-
查询博客
-
该查询的要求,要求在author或者title不为空的时候,进行相应的详细查询
-
<select id="getBlogIf" resultType="Blog" parameterType="java.util.Map"> select * from blog where true <if test="author != null"> and author = #{author} </if> <if test="title != null"> and title = #{title} </if> </select>
set的学习
-
根据要求来进行博客信息的更新
-
<update id="updateBlogMessage" parameterType="java.util.Map"> update blog <set> <if test="author != null"> author = #{author} </if> </set> where id = #{id} </update>
choose和otherwise相关
-
<select id="test" resultType="Blog" parameterType="user"> select * from blog <where> <choose> <when test="title != null"> </when> <when test="author != null"> </when> <otherwise> </otherwise> </choose> </where> </select>
foreach相关
-
案例:来查询id为哪几位的几条数据,通过foreach来进行传参。
-
Map<String, List<Integer>> map = new HashMap<>(); List<Integer> numList = new ArrayList<>(); for (int i = 5; i > 0; i --) { numList.add(i); } map.put("ids", numList); List<Blog> blogBetweenRange = mapper.getBlogBetweenRange(map);
<select id="getBlogBetweenRange" resultType="Blog" parameterType="java.util.Map"> select * from blog <where> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id = #{id} </foreach> </where> </select>
总结:所谓的动态SQL,本质上还是SQL语句的拼接,只是我们在SQL语句的层面上去加入了一个执行逻辑的控制代码。
最后再给大家插播一条小知识:
长知识时间:HashMap的默认大小是2^4也就是16,最大的大小是2^30,并且hashmap的大小只能是2的次方数个。ArrayList的默认大小是10。