【Mybatis】(六)动态SQL

简介: 【Mybatis】(六)动态SQL

1、定义EmployeeMapperDynamicSQL接口


package com.lhk.mybatis.dao;
        import com.lhk.mybatis.bean.Employee;
        import org.apache.ibatis.annotations.Param;
        import java.util.List;
        public interface EmployeeMapperDynamicSQL {
            // 查询员工,要求携带了哪个字段查询字段就带上这个字段的值,测试where
            public List<Employee> getEmpByConditionIf(Employee employee);
            // 查询员工,测试Trim
            public List<Employee> getEmpByConditionTrim(Employee employee);
            // 查询员工,测试Choose,When,otherwise
            public List<Employee> getEmpByConditionChoose(Employee employee);
            // 更新员工信息
            public void updateEmp(Employee employee);
            // 插入员工信息
            public void insertEmp(Employee employee);
            // 通过foreach在指定集合中查询员工id
            public List<Employee> getEmpByConditionForeach(@Param("ids") List<Integer> id);
            // 通过foreach批量插入员工信息
            public void addEmp(@Param("emps") List<Employee> employee);
        }


2、定义EmployeeMapperDynamicSQL.xml配置文件


<?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.lhk.mybatis.dao.EmployeeMapperDynamicSQL">
        <!--
            • if 判断
            • choose (when, otherwise) 分支选择(带了break的switch-case)
                如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个
            • trim (where(封装查询条件), set(封装修改条件)) 字符串截取
            • foreach
        -->
        <resultMap id="Simple" type="com.lhk.mybatis.bean.Employee">
            <result column="last_name" property="lastName"></result>
        </resultMap>
        <!--查询员工,要求携带了哪个字段查询字段就带上这个字段的值
            getEmpByConditionIf
        -->
        <select id="getEmpByConditionIf" resultMap="Simple">
            select * from tb1_employee
    --         where
            <where>
                <!--
                测试where:
                1、当if条件不满足,即where元素中没有内容,在SQL语句中就不会出现where
                2、当if条件满足,where元素的内容是以and开头,where会自动去掉开头的and or,以保证where条件正确
                3、where不能解决SQL语句后面多出的and or,要通过trim解决
                test:判断表达式,从参数中取值进行判断-->
                <if test="id!=null">
                    id=#{id}
                </if>
                <if test="lastName!=null and lastName!=''">
                    and last_name like #{lastName}
                </if>
                <if test="email!=null and email.trim()!=''">
                    and email=#{email}
                </if>
                <if test="gender==0 and gender==1">
                    and gender=#{gender}
                </if>
            </where>
        </select>
        <!--通过Trim方式 getEmpByConditionTrim -->
        <select id="getEmpByConditionTrim" resultMap="Simple">
            select * from tb1_employee
            --         where
            <!--
                where,set标签的功能都可以通过Trim来实现
                解决SQL语句后面多出的and or,where标签不能解决
            <trim prefix="" 前缀,当trim元素内包含内容时,会给内容增加prefix指定的前缀
                  prefixOverrides="" 前缀覆盖,当trim元素内包含内容时,会把内容中匹配的前缀字符串去掉
                  suffix="" 后缀,当trim元素内包含内容时,会给内容增加suffix指定的后缀
                  suffixOverrides="" 后缀覆盖,当trim元素内包含内容时,会把内容中匹配的后缀字符串去掉
            </trim>
            -->
            <!--自定义字符串截取规则-->
            <!--在SQL语句前面添加where,去除SQL语句中后面多余的and -->
            <trim prefix="where" prefixOverrides="" suffix="" suffixOverrides="and">
                <!-- test:判断表达式,从参数中取值进行判断-->
                <if test="id!=null">
                    id=#{id} and
                </if>
                <if test="lastName!=null and lastName!=''">
                    last_name like #{lastName} and
                </if>
                <if test="email!=null and email.trim()!=''">
                    email=#{email} and
                </if>
                <if test="gender==0 and gender==1">
                    gender=#{gender}
                </if>
            </trim>
        </select>
        <!--测试分支选择 getEmpByConditionChoose -->
        <select id="getEmpByConditionChoose" resultMap="Simple">
            select * from tb1_employee
            <where>
                <!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 -->
                <choose>
                    <when test="id!=null">
                        id=#{id}
                    </when>
                    <when test="lastName!=null">
                        last_name like #{lastName}
                    </when>
                    <when test="email!=null">
                        email=#{email}
                    </when>
                    <otherwise>
                        gender=0
                    </otherwise>
                </choose>
            </where>
        </select>
        <!-- 测试update  updateEmp
            只更新要更新的值。为null的值就不更新
            set:1、如果该标签包含的元素中有返回值,就插入一个set
                 2、如果set后面的字符串是以逗号结尾,就删除这个逗号
                 3、如果set元素中没有内容,则仍然会出现SQL错误,所以id=#{id}仍有保留的必要
         -->
        <update id="updateEmp">
            update tb1_employee
            <set>
                <if test="lastName!=null">
                    last_name=#{lastName},
                </if>
                <if test="email!=null">
                    email=#{email},
                </if>
                <if test="gender!=null">
                  gender=#{gender}
                </if>
                id=#{id},
            </set>
            where id=#{id}
        </update>
        <!--测试insert insertEmp
            只插入要插入的值。为null的值就不插入。
            在列的部分增加if条件,则values的部分也要增加相同的if条件,
            必须保证上下相互对应,完全匹配
        -->
        <insert id="insertEmp">
            insert into tb1_employee(
            <if test="id!=null and id!=''">
                id,
            </if>
            <if test="lastName!=null and lastName!=''">
                last_name,
            </if>
            <if test="email!=null and email!=''">
                email,
            </if>
            <if test="gender!=null and gender!=''">
                gender
            </if>
            )
            <trim suffixOverrides=",">
                values(
                <if test="id!=null and id!=''">
                    #{id},
                </if>
                <if test="lastName!=null and lastName!=''">
                    #{lastName},
                </if>
                <if test="email!=null and email!=''">
                    #{email},
                </if>
                <if test="gender!=null and gender!=''">
                    #{gender}
                </if>
                )
            </trim>
        </insert>
        <!--测试foreach getEmpByConditionForeach-->
        <!--
            collection:指定要遍历的集合,
                   list类型的参数会特殊处理封装在map中,map的key就叫list
            item:将当前遍历出的元素赋值给指定的变量
            separate:每个元素之间的分隔符
            open:遍历出所有的结果拼接一个开始字符
            close:遍历出所有的结果拼接一个结束字符
            index:遍历list的时候,index是list的索引,item是list的值
                   遍历map的时候,index是map的key,item是map的值
        -->
        <select id="getEmpByConditionForeach" resultMap="Simple">
            select * from tb1_employee where id in
            <foreach collection="ids" item="item_id" separator="," open="(" close=")">
                #{item_id}
            </foreach>
        </select>
        <!-- 批量保存:addEmp-->
        <insert id="addEmp">
            insert into tb1_employee(last_name,email,gender,d_id)
            values
            <foreach collection="emps" item="emp" separator=",">
                (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
            </foreach>
        </insert>
    </mapper>


3、定义MybatisDynamicSQLTest测试类


package com.lhk.mybatis.test;
import com.lhk.mybatis.bean.Department;
import com.lhk.mybatis.bean.Employee;
import com.lhk.mybatis.dao.EmployeeMapperDynamicSQL;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MybatisDynamicSQLTest {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "conf/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }
    /**
     * 测试If
     */
    @Test
    public void testgetEmpByConditionIf() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);
            Employee employee = new Employee(2,"%e%","Jerry@qq.com","1");
            List<Employee> list = mapper.getEmpByConditionIf(employee);
            for (Employee emp : list) {
                System.out.println(emp);
            }
            //查询的时候如果某些条件没有,SQL拼装可能会出问题
            //1、给where后面加上1=1,以后的条件都and xxx
            //2、mybatis使用where标签将所有的查询条件包括在内
            //mybatis就会将where标签中的拼装的SQL中多的and,or去掉。只会去掉第一个多出来的and,or
        }finally {
            sqlSession.close();
        }
    }
    /**
     * 测试Trim
     */
    @Test
    public void testGetEmpByConditionTrim() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);
            Employee employee = new Employee(null, "%e%", "Jerry@qq.com", "1");
            List<Employee> list = mapper.getEmpByConditionTrim(employee);
            for (Employee emp : list) {
                System.out.println(emp);
            }
        }finally {
            sqlSession.close();
        }
    }
    /**
     * 测试Choose
     */
    @Test
    public void testGetEmpByConditionChoose() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);
            Employee employee = new Employee(null, null, "Jerry@qq.com", "1");
            List<Employee> list = mapper.getEmpByConditionChoose(employee);
            for (Employee emp : list) {
                System.out.println(emp);
            }
        }finally {
            sqlSession.close();
        }
    }
    /**
     * 测试set
     */
    @Test
    public void testUpdateEmp() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);
            Employee employee = new Employee(null, null, null, null);
            mapper.updateEmp(employee);
            sqlSession.commit(); // 提交
        }finally {
            sqlSession.close();
        }
    }
    /**
     * 测试insert
     */
    @Test
    public void testInsertEmp() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);
            Employee employee = new Employee(null, "lll", null, "0");
            mapper.insertEmp(employee);
            sqlSession.commit(); // 提交
        }finally {
            sqlSession.close();
        }
    }
    /**
     * 测试foreach实现in集合
     */
    @Test
    public void testGetEmpByConditionForeach() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);
            List<Employee> list = mapper.getEmpByConditionForeach(Arrays.asList(2,6));
            for (Employee emp : list) {
                System.out.println(emp);
            }
        }finally {
            sqlSession.close();
        }
    }
    /**
     * 测试foreach实现批量插入
     */
    @Test
    public void testBatchSave() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);
            List<Employee> emps = new ArrayList<>();
            emps.add(new Employee(null,"Smith","Smith@qq.com","1",new Department(1)));
            emps.add(new Employee(null,"Tom","Tom@qq.com","0",new Department(2)));
            mapper.addEmp(emps);
            sqlSession.commit(); //提交
        }finally {
            sqlSession.close();
        }
    }
}



目录
相关文章
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
8月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
486 18
|
SQL Java 数据库连接
MyBatis动态SQL字符串空值判断,这个细节99%的程序员都踩过坑!
本文深入探讨了MyBatis动态SQL中字符串参数判空的常见问题。通过具体案例分析,对比了`name != null and name != &#39;&#39;`与`name != null and name != &#39; &#39;`两种写法的差异,指出后者可能引发逻辑混乱。为避免此类问题,建议在后端对参数进行预处理(如trim去空格),简化MyBatis判断逻辑,提升代码健壮性与可维护性。细节决定成败,严谨处理参数判空是写出高质量代码的关键。
1595 0
|
8月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
324 0
|
11月前
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
1060 5
|
SQL Java 数据库连接
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
SQL XML Java
九、MyBatis动态SQL
九、MyBatis动态SQL
229 2
|
SQL Java 数据库连接
【潜意识Java】MyBatis中的动态SQL灵活、高效的数据库查询以及深度总结
本文详细介绍了MyBatis中的动态SQL功能,涵盖其背景、应用场景及实现方式。
1799 6
|
SQL XML Java
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
448 0
下一篇
开通oss服务