MyBatis学习(十五)——动态SQL(if,where,choose,set,trim,foreach)

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

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

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

在这里插入图片描述
在这里插入图片描述
在核心配置文件中设置
在这里插入图片描述

导包和之前的项目一样

配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>

    <!--  引入外部配置文件-->
    <properties resource="pp.properties"/>

    <settings>
        <!--    标准的日志工厂-->

        <setting name="logImpl" value="STDOUT_LOGGING"/>
       <!-- <setting name="logImpl" value="LOG4J"/>-->

    </settings>


    <!--给实体类起别名-->
    <typeAliases>

        <package name="com.my.pojo"/>
    </typeAliases>



    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/><!--事务管理-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

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

    </mappers>


</configuration>
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&userUnicode=true&characterEncoding=UTF-8
username=root
password=123456

在这里插入图片描述

实体类

import lombok.Data;

import java.util.Date;
@Data
public class Blog {
    
    
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;

}


连接类
在这里插入图片描述

package com.my.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//sqlSessionFactory  构建sqlSession
public class MybatisUtils {
    
    
    private static SqlSessionFactory sqlSessionFactory;
    static {
    
    
        try{
    
    
            //使用mybatis第一步 获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
    
    
        return sqlSessionFactory.openSession(true);
    }
}

接口和xml

package com.my.dao;

public interface BlogMapper {
    
    
}

<?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.my.dao.BlogMapper" >




</mapper>

插入数据

在这里插入图片描述

测试代码

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

import java.util.Date;

public class MyTest {
    
    
    @Test
    public void addBlogTest(){
    
    
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("狂神");
        blog.setCreateTime(new Date());
        blog.setViews(9999);
        mapper.addBook(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("Java");
        mapper.addBook(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("Spring");
        mapper.addBook(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("微服务");
        mapper.addBook(blog);

       // 因为在前面的连接中设置自动提交事务所以这里不用commit
        sqlSession.close();

    }
}

在这里插入图片描述

动态SQL之if

在这里插入图片描述

在这里插入图片描述

使用where标签

如果两个条件都成立,where标签会自动将第一个语句的起始and去掉,如果都不成立,会自动将where去掉
在这里插入图片描述

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

    </select>

在这里插入图片描述

在这里插入图片描述

条件成立进入if标签
在这里插入图片描述
在这里插入图片描述

动态SQL之choose (when, otherwise)

在这里插入图片描述

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

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

set标签

在这里插入图片描述
只要满足if的条件就可以拼接在sql中,最后一个修改的内容后不加逗号
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

trim标签

在这里插入图片描述
在这里插入图片描述

SQL片段

可以使用sql标签解决代码复用问题

  • 使用sql标签抽取公共的部分
  • 在需要使用的地方使用include标签引用即可

最好基于单表来定义SQL
不要存在where标签,因为where涉及一些条件的判断

在这里插入图片描述

foreach

在这里插入图片描述
在这里插入图片描述

 <!--select * from mybatis.blog where in(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>

 @Test
    public void queryBlogForeach(){
    
    
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        List<Integer> ids = new ArrayList<Integer>();
        map.put("ids",ids);
        ids.add(1);
        ids.add(2);
        ids.add(4);

        List<Blog> blogList = mapper.queryBlogForeach(map);
        for (Blog blog : blogList) {
    
    
            System.out.println(blog);
        }
        sqlSession.close();
    }

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/char_m/article/details/111499413