• Mybatis: (八)动态sql


    一、前言

    动态sql是指根据不同的查询条件,生成不同的sql语句

       - if
        - choose (when, otherwise)
        - trim (where, set)
        - foreach
    

    二、实现

    字段:id,title,author,create_time,views

    1. 建表
    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
    
    1. IDutil工具类
    public class IDUtil {
    
        public static String genId(){
            return UUID.randomUUID().toString().replaceAll("-","");
        }
    
    }
    
    1. 实体类
    import java.util.Date;
    
    public class Blog {
    
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
        //set,get....
    }
    
    1. 创建Mapper接口
    List<Blog> queryBlogIf(Map map);
    
    1. 编写sql语句

      if语句

    <!--需求1:
    根据作者名字和博客名字来查询博客!
    如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
    select * from blog where title = #{title} and author = #{author}
    -->
    <select id="queryBlogIf" parameterType="map" resultType="blog">
        select * from blog where
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>
    

    测试

    @Test
    public void testQueryBlogIf(){
        SqlSession session = MybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
    
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("title","三体");
        map.put("author","刘慈欣");
        List<Blog> blogs = mapper.queryBlogIf(map);
    
        System.out.println(blogs);
    
        session.close();
    }
    

    where语句

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

    “where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

    set语句

    <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>
    

    choose语句

    List<Blog> queryBlogChoose(Map map);

    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <choose>
            //when只要成立,后面的不再判断
                <when test="title != null">
                     title = #{title}
                </when>
                <when test="author != null">
                    and author = #{author}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>
    

    sql片段

    <sql id="if-title-author">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>
    
    <select id="queryBlogIf" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
            <include refid="if-title-author"></include>
        </where>
    </select>
    

    foreach

    List<Blog> queryBlogForeach(Map map);
    
    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from blog where 1=1 and (id=1 or id=2 or id=3)
          -->
            <foreach collection="ids"  item="id" open="and (" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>
    
    @Test
    public void testQueryBlogForeach(){
        SqlSession session = MybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
    
        HashMap map = new HashMap();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids",ids);
    
        List<Blog> blogs = mapper.queryBlogForeach(map);
    
        System.out.println(blogs);
    
        session.close();
    }
    

    bind

    <select id="selectBlogsLike" resultType="Blog">
      <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
      SELECT * FROM BLOG
      WHERE title LIKE #{pattern}
    </select>
    
  • 相关阅读:
    mui 上拉加载 实现分页加载功能
    CSS 实现自适应正方形
    CSS 实现垂直居中
    CSS 实现左侧固定,右侧自适应两栏布局的方法
    微信小程序 主题皮肤切换(switch开关)
    微信小程序 tabBar模板
    微信小程序 拼团商品倒计时(拼团列表、拼团商品详情)
    js时间操作getTime(),ios移动端真机上返回显示NAN
    微信小程序 使用wxParse解析html
    原生JavaScript轮播图的节流
  • 原文地址:https://www.cnblogs.com/dreamzone/p/12358440.html
Copyright © 2020-2023  润新知