MyBatis之动态SQL

八、动态SQL

目录:介绍及环境搭建、IF、choose (when, otherwise)、trim (where,set)、SQL片段、Foreach

1.介绍及环境搭建

什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句。
动态SQL元素和JSTL或基于类似XML的文本处理器相似。在MyBatis之前的版本中,有很多元素需要花时间了解。MyBatis3大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis采用功能强大的基于OGNL的表达式来淘汰其它大部分元素。

CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL COMMENT '博客id',
  `title` varchar(100) NOT NULL COMMENT '博客标题',
  `author` varchar(30) NOT NULL COMMENT '博客作者',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8

创建基础工程
①导包。
②编写配置文件。
③编写实体类和获取id的方法。

package com.ping.pojo;
import lombok.Date;
import java.util.Date;
@Date
public class Blog {
  private String id;
  private String title;
  private String author;
  private Date createTime;
  private int views;
}

IDutils.java:

package com.ping.utils;
import org.junit.Test;
import java.util.UUID;
@SuppressWarnings("all")//抑制警告
public class IDutils {
  public static String getId() {
    return UUID.randomUUID().toString().replaceAll("-","");
  }
  @Test
  public void test() {
    System.out.println(IDutils.getId());
  }
}

④编写实体类对应Mapper接口和Mapper.xml文件。
BlogMapper.java:

package com.ping.dao;
import com.ping.pojo.Blog;
public interface BlogMapper {
  //插入数据
  int addBlog(Blog blog);
}

BlogMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ping.dao.Blogapper">
  <insert id="addBlog" parameterType="blog">
    insert into mybatis.blog (id, title, author, create_time, views) values (#{id}, #{title}, #{author}, #{createTime}, #{view});
  </insert>
</mapper>

⑤测试并插入数据。

import com.ping.dao.BlogMapper;
import com.ping.pojo.Blog;
import com.ping.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class TestDate {
  @Test
  public void addInitBlog() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper =sqlSession.getMapper(BlogMapper.class);
    Blog blog = new Blog();
    blog.setId(IDutils.getId());
    blog.setTitle("Java如此简单");
    blog.setAuthor("Ping");
    blog.setCreateTime(new Date());
    blog.setViews(9999);
    mapper.addBlog(blog);
    blog.setId(IDutils.getId());
    blog.setTitle("MyBatis如此简单");
    mapper.addBlog(blog);
    blog.setId(IDutils.getId());
    blog.setTitle("Spring如此简单");
    mapper.addBlog(blog);
    blog.setId(IDutils.getId());
    blog.setTitle("SpringMVC如此简单");
    mapper.addBlog(blog);
    sessin.close();
  }
}

2.IF

1)编写实体类对应Mapper接口
BlogMapper.java:

package com.ping.dao;
import com.ping.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
  //查询博客中的数据
  List<Blog> queryBlogIF(Map map);
}

2)编写Mapper.xml文件中的查询语句

<select id="queryBlogIF" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <if test="title != null">
    title = #{title}
  </if>
  <if test="author != null">
    and author = #{author}
  </if>
</select>

3)测试查询

import com.ping.dao.BlogMapper;
import com.ping.pojo.Blog;
import com.ping.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class TestDate {
  @Test
  public void queryBlogIF() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper =sqlSession.getMapper(BlogMapper.class);  
    HashMap map = new HashMap();
    //map.put("title","Java如此简单");
    map.put("author","Ping");
    List<Blog> blogs = mapper.queryBlogIF(map);
    for (Blog blog : blogs) {
      System.out.println(blog);
    }
    sqlSession.close();
  }
}

3.choose (when, otherwise)

MyBatis提供了choose元素,它有点像Java中的switch语句。
1)编写实体类对应Mapper接口
BlogMapper.java:

package com.ping.dao;
import com.ping.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
  //查询博客中的数据
  List<Blog> queryBlogChoose(Map map);
}

2)编写Mapper.xml文件中的查询语句

<select id="queryBlogChoose" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <where>
    <choose>
      <when test="title != null">
        title = #{title}
      </when>
      <when test="author != null">
        and author = #{author}
      </when>
      <otherwise>
        and views = #{views}
      </otherwise>
    </choose>
  </where>
</select>

4.trim (where,set)

1)where
where元素只会在至少有一个子元素的条件返回SQL子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where元素也会将它们去除。

<select id="queryBlogIF" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <where>
    <if test="title != null">
      title = #{title}
    </if>
    <if test="author != null">
      and author = #{author}
    </if>
  </where>
</select>

2)set
set元素会动态前置SET关键字,同时也会删掉无关的逗号。
①编写实体类对应Mapper接口
BlogMapper.java:

package com.ping.dao;
import com.ping.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
  //更新博客中的数据
  int updateBlog(Map map);
}

②编写Mapper.xml文件中的查询语句

<update id="updateBlog" parameterType="map">
  update mybatis.blog
  <set>
    <if test="title != null">
      title = #{title},
    </if>
    <if test="author != null">
      author = #{author}
    </if>
  </set>
  where id = #{id}
</update>

3)trim
语法

<trim prefix="" prefixOverrides="" suffix="" suffixOverrides="">
</trim>

①如果where元素没有按正常的套路出牌,可以通过自定义trim元素来定制where元素功能。比如,和where元素等价的定义trim元素为:

<trim prefix="WHERE" prefixOverrides="AND | OR ">
</trim>

prefixOverrides属性会忽略通过管道分割的文本序列(注意此例中的空格也是必要的)。它的作用是移除所有指定在prefixOverrides属性中的内容,并且插入prefix属性中的指定内容。
②同时,set也有这样的操作。

<trim prefix="SET" suffixOverrides=",">
</trim>

总结:所谓的动态SQL,本质还是SQL语句, 只是可以在SQL层面去执行一个逻辑代码。

5.SQL片段

有的时候,可以将一些功能的部分抽取出来,方便复用。如:
①使用SQL标签抽取公共的部分。

<sql id="if-title-author">
  <if test="title != null">
    title = #{title}
  </if>
  <if test="author != null">
    and author = #{author}
  </if>
</sql>

②在需要使用的地方使用include标签引用即可。

<select id="queryBlogIF" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <where>
    <include refid="if-title-author"></include>
  </where>
</select>

注意:Ⅰ最好基于单表来定义SQL片段。
Ⅱ不要存在where标签。

6.Foreach

动态SQL里的常用操作需求是对一个集合进行遍历,通常是在构建IN条件语句的时候。

<!--
  select * from mybatis.blog where 1=1 and (id=1 or id = 2 or id=3)
  传递一个万能的map , 这个map中可以存在一个集合
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <where>
    <foreach collection="ids" item="id" open="and (" close=")" separator="or">
      id = #{id}
    </foreach>
  </where>
</select>

总结:动态SQL就是在拼接SQL语句,只要保证SQL的正确性,按照SQL的格式去排列组合就可以了。
建议:现在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值