Mybatis08--动态sql

动态SQL

动态SQL:就是根据不同的条件生成不同的SQL语句

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

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

搭建环境

结构:
在这里插入图片描述

数据表:

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 '创建时间',
	`view` int(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

生成随机uid工具类

package com.shy.utils;
import java.util.UUID;
@SuppressWarnings("all")//抑制警告
public class IDutils {
    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}

创建一个基础工程

编写BlogMapper接口

package com.shy.dao;
import com.shy.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
    //插入树控件
    int addBlog(Blog blog);
    //更新博客
    int updateBlog(Map map);
    //查询博客
    List<Blog> queryBlogIF(Map map);
    List<Blog> queryBlogChoose(Map map);
    //查询第1,2,3号记录的博客
    List<Blog> queryBlogForeach(Map map);
}

实体类

@Data
public class Blog {
    private int id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

编写对应的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">
<!--configuration核心配置文件-->
<mapper namespace="com.shy.dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
        insert into blog (id,title,author,create_time,views)
        values (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
	<!--trim、where、set-->
    <select id="queryBlogIF" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <if test="title != null">
                and title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if>
        </where>
    </select>
	<!--choose、when、otherwise-->
    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                    title = #{title}
                </when>
                <when test="author">
                    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>
    <!--foreach-->
    <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>
</mapper>

settings

配置mybatis-config.xml

	<!--引入外部配置文件:之前写过,直接拿来用-->
    <properties resource="db.properties"/>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
	<!--可以给实体类取别名-->
    <typeAliases>
        <package name="com.shy.pojo"/>
    </typeAliases>

	...

	<mappers>
        <mapper class="com.shy.dao.BlogMapper"/>
    </mappers>

测试:

import com.shy.dao.BlogMapper;
import com.shy.pojo.Blog;
import com.shy.utils.IDutils;
import com.shy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MyTest {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        blog.setId(IDutils.getId());
        blog.setTitle("aaa");
        blog.setAuthor("shy");
        blog.setCreateTime(new Date());
        blog.setViews(999);
        mapper.addBlog(blog);

        Blog blog2 = new Blog();
        blog2.setId(IDutils.getId());
        blog2.setTitle("bbbaaa");
        blog2.setAuthor("hy");
        blog2.setCreateTime(new Date());
        blog2.setViews(999);
        mapper.addBlog(blog2);

        Blog blog3 = new Blog();
        blog3.setId(IDutils.getId());
        blog3.setTitle("我是aaa");
        blog3.setAuthor("sy");
        blog3.setCreateTime(new Date());
        blog3.setViews(999);
        mapper.addBlog(blog3);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void queryBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        //map.put("title","who");
        map.put("author","shy2");
        map.put("id","看数据表中生成的id,写上就行");
        mapper.updateBlog(map);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void queryBlogForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        //这里由于生成的id过长,所以我直接修改了表中的id为123...
        ids.add(1);
        ids.add(2);
        map.put("ids",ids);
        List<Blog> blogs = mapper.queryBlogForeach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
}

所谓的动态sql本质上还是sql语句,只是我们可以在sql层面可以执行一个逻辑代码

SQL片段

将一些功能的部分抽取出来,方便复用

1.使用sql标签抽取公共的部分

<sql id=""></sql>

2.在需要使用的地方用include标签引用即可

注意:

1.最好基于单表定义sql片段

2.标签内部不要存在where标签

动态sql就是在拼接sql语句,只要保证他的正确性,按照sql的格式,去排列组合就可以了。

先在Mysql中写出完整的sql,再对应的去修改动态sql实现通用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值