<select id="getBlogIF" parameterType="map" resultType="com.xu.pojo.Blog"> select * from blog where 1=1 <if test="title !=null"> and title =#{title} </if> <if test="author !=null"> and author =#{author} </if> </select>
<select id="queryBlogChoose" parameterType="map" resultType="blog"> select * from blog <where> <choose> <when test="title !=null"> title =#{title} </when> <when test="author !=nuu"> and author =#{author} </when> <otherwise> and views = #{views} </otherwise> </choose> </where> </select>
<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>
接口:
public interface BlogMapper { //插入数据 int addBlog(Blog blog); //查询博客 List<Blog>getBlogIF(Map map); Blog BlogBYID(int views); // List<Blog>queryBlogChoose(Map map); //更新博客 int updateBlog(Map map); }
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQl层面,去执行一个逻辑代码
if
where ,set choose,when
Foreach
<select id="queryBlogForeach" parameterType="map" resultType="blog"> select * from blog <where> <foreach collection="ids" item="id" open="(" close=")" separator="or"> id = #{id} </foreach> </where> </select>
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
<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>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
至此,我们已经完成了与 XML 配置及映射文件相关的讨论。下一章将详细探讨 Java API,以便你能充分利用已经创建的映射配置。
select * from user where 1=1 and (id=1 or id = 2 orid =3)
SQl片段
有时候,我们可能会将一些功能的部分抽取出来,方便复用!
1.使用SQl标签抽取公共的部分
<sql id="if-title-author"> <if test="title !=null"> and title =#{title} </if> <if test="author !=null"> and author =#{author} </if> </sql>
2.在需要使用的地方使用include标签引用即可
<select id="getBlogIF" parameterType="map" resultType="com.xu.pojo.Blog"> select * from blog <where> <include refid="if-title-author"></include> </where> </select>
注意事项:
最好基于单表来定义来SQL片段!
不要存在where标签