无所畏惧,坚持到底,决不放弃。干兄弟们
什么是动态sql,动态sql就是根据不同的条件产生不同的sql语句
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
CREATE TABLE `mybatis`.`blog` (
`id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '博客id',
`title` VARCHAR(30) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量',
PRIMARY KEY (`id`)
)
创建一个基础工程
select * from blog where 1=1
and title = #{title};
and author = #{author};
<select id="queryBlogChoose" resultType="blog" parameterType="map">
select * from blog
<where>
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
select * from blog
and title = #{title};
and author = #{author};
<update id="UpdateBlog" parameterType="map" >
update blog
<set>
<if test="title != null">
title = #{title},
if>
<if test="author != null">
author = #{author}
if>
set>
where id = #{id}
update>
所谓的动态sqL,本质上就是sql语句,只是我们可以在sql层面,去执行一个逻辑代码
有的时候,我们可能会将一些公共的部分抽取出来,方便使用
通过include标签的refid属性来调用sql片段
<select id="queryBlogif" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author">include>
where>
select>
设置id来让sql片段可以被调用,
<sql id="if-title-author">
<if test="title != null">
and title = #{title};
if>
<if test="author != null">
and author = #{author};
if>
sql>
注意事项:
select * from User where 1=1 and (id = 1 or id=2 or id=3)
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
foreach>
select>
<select id="queryBlogForeach" resultType="blog" parameterType="map">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
foreach>
where>
select>
建议: