mybatis中的动态sql问题怎么解决

本篇内容主要讲解“mybatis中的动态sql问题怎么解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“mybatis中的动态sql问题怎么解决”吧!

    Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是通过标签解决拼接SQL语句字符串时的问题

    1、if(常用)

    if:根据标签中test属性所对应的表达式决定标签中的内容是否需要拼接到SQL中

    /**
         * 多条件查询
         */
        List<Emp> getEmpByCondition(Emp emp);

    当empName为null和“ ”时,会拼接and age,此时会报错,可以1=1恒成立解决。

    • 用and表示&&(并且)

    • emp_name是字段名

    • if只有test标签且必须使用

    <!--List<Emp> getEmpListByMoreTJ(Emp emp);-->
        <select id="getEmpListByMoreTJ" resultType="Emp">
    select * from t_emp where 1=1
    <if test="empName!= '' and empName!= null">
        and emp_name = #{empName}
    </if>
    <if test="age != '' and age != null">
        and age = #{age}
    </if>
    <if test="sex != '' and sex != null">
        and sex = #{sex}
    </if>
    </select>
    @Test
        public void testGetEmpByCondition(){
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
            List<Emp> list = mapper.getEmpByCondition(new Emp(null, "陈智", 33, "女", null));
            System.out.println(list);
        }
    select eid,emp_name,age,sex,email from t_emp where emp_name = ? and age = ? or sex = ?

    2、where

    当where标签中有内容时,会自动生成where关键字,并且将内容前多余的and或or去掉(在程序执行后生成的sql会将内容前多余的and或or去掉)

    and写在第二句是为了和上面拼接,写在第一句是和下面拼接(即固定有elect * from t_emp emp_name= ?)

    <select id="getEmpListByMoreTJ2" resultType="Emp">
        select * from t_emp
    <where>
    <if test="empName != '' and empName != null">
        emp_name = #{empName }
    </if>
    <if test="age != '' and age != null">
        and age = #{age}
    </if>
    <if test="sex != '' and sex != null">
        and sex = #{sex}
    </if>
    </where>
    </select>

    当where标签中没有内容时(或者使用getEmpByCondition传入的值全为null或“ ”),此时where标签没有任何效果。则直接SQL语句为select * from t_emp

    --------------------分割--------------------

    where标签不能将其中内容后面多余的and或or去掉:(会报错)

    语句为select * from t_emp emp_name= ? and

    <select id="getEmpListByMoreTJ2" resultType="Emp">
        select * from t_emp
    <where>
    <if test="empName != '' and empName != null">
        emp_name = #{empName } and
    </if>
    <if test="age != '' and age != null">
        age = #{age} and
    </if>
    <if test="sex != '' and sex != null">
        sex = #{sex}
    </if>
    </where>
    </select>

    3、trim

    where的增强

    若标签中有内容时:

    • prefix|suffix:将trim标签中内容前面或后面添加指定内容

    • suffixOverrides|prefixOverrides:将trim标签中内容前面或后面去掉指定内容

    若标签中没有内容时,trim标签也没有任何效果(跟上面的where一样)

    <!--List<Emp> getEmpByCondition(Emp emp);-->
        <select id="getEmpByCondition" resultType="Emp">
            select <include refid="empColumns"></include> from t_emp
            <trim prefix="where" suffixOverrides="and|or">
                <if test="empName != null and empName != ''">
                    emp_name = #{empName} and
                </if>
                <if test="age != null and age != ''">
                    age = #{age} or
                </if>
                <if test="sex != null and sex != ''">
                    sex = #{sex} and
                </if>
                <if test="email != null and email != ''">
                    email = #{email}
                </if>
            </trim>
        </select>

    4.choose、when、otherwise

    相当于if...else if...else

    /**
         * 测试choose、when、otherwise
         */
        List<Emp> getEmpByChoose(Emp emp);

    when至少要有一个,otherwise最多只能有一个

    与第一点if的区别:choose只会满足一个条件便退出,一个不满足则执行otherwise

    <!--List<Emp> getEmpByChoose(Emp emp);-->
        <select id="getEmpByChoose" resultType="Emp">
            select * from t_emp
            <where>
                <choose>
                    <when test="empName != null and empName != ''">
                        emp_name = #{empName}
                    </when>
                    <when test="age != null and age != ''">
                        age = #{age}
                    </when>
                    <when test="sex != null and sex != ''">
                        sex = #{sex}
                    </when>
                    <when test="email != null and email != ''">
                        email = #{email}
                    </when>
                    <otherwise>
                        did = 1
                    </otherwise>
                </choose>
            </where>
        </select>
    @Test
        public void testGetEmpByChoose(){
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
            List<Emp> list = mapper.getEmpByChoose(new Emp(null, "", null, "", ""));
            System.out.println(list);
        }

    mybatis中的动态sql问题怎么解决

    5、foreach

    • collection:设置需要循环的数组或集合

    • item:表示数组或集合中的每一个数据

    • separator:循环体之间的分割符

    • open:foreach标签所循环的所有内容的开始符

    • close:foreach标签所循环的所有内容的结束符

    5.1批量删除

    /**
         * 通过数组实现批量删除
         */
        int deleteMoreByArray(@Param("eids") Integer[] eids);
    <!--int deleteMoreByArray(@Param("eids") Integer[] eids);-->
        <delete id="deleteMoreByArray">
            delete from t_emp where
            <foreach collection="eids" item="eid" separator="or">
                eid = #{eid}
            </foreach>
            <!--
                delete from t_emp where eid in
                <foreach collection="eids" item="eid" separator="," open="(" close=")">
                    #{eid}
                </foreach>
            -->
        </delete>
    @Test
        public void testDeleteMoreByArray(){
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
            int result = mapper.deleteMoreByArray(new Integer[]{12,13,14,15});
            System.out.println(result);
        }

    mybatis中的动态sql问题怎么解决

    5.2批量添加

    /**
         * 通过list集合实现批量添加
         */
        int insertMoreByList(@Param("emps") List<Emp> emps);
    <!--int insertMoreByList(@Param("emps") List<Emp> emps);-->
        <insert id="insertMoreByList">
            insert into t_emp values
            <foreach collection="emps" item="emp" separator=",">
                (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
            </foreach>
        </insert>

    Arrays.asList该方法是将数组转化成List集合的方法 

    如果你的List只是用来遍历,就用Arrays.asList()。

    如果你的List还要添加或删除元素,还是乖乖地new一个java.util.ArrayList,然后一个一个的添加元素。

    @Test
        public void testInsertMoreByList(){
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
            Emp emp1 = new Emp(null,"a1",23,"男","123@qq.com");
            Emp emp2 = new Emp(null,"a2",23,"男","123@qq.com");
            Emp emp3 = new Emp(null,"a3",23,"男","123@qq.com");
            List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
            System.out.println(mapper.insertMoreByList(emps));
        }

    6、sql标签

    设置SQL片段:<sql id="empColumns">eid,emp_name,age,sex,email</sql>

    引用SQL片段:<include refid="empColumns"></include>

    mybatis中的动态sql问题怎么解决

    到此,相信大家对“mybatis中的动态sql问题怎么解决”有了更深的了解,不妨来实际操作一番吧!这里是编程之家网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

    版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

    相关推荐


    1.pom.xml引入依赖 &lt;dependency&gt; &lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt; &lt;artifactId&gt;pagehelper&lt;/artifactId&gt; &lt;version&gt;5
    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;!DOCTYPE configuration PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot; &qu
    准备工作 ① 创建数据库&amp;数据表 ## 创建数据库 CREATE DATABASE `dbtest1`; ## 创建数据表 CREATE TABLE `t_user` ( `id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(20) DEF
    MyBatis逆向工程是指根据数据库表结构自动生成对应的实体类、Mapper接口以及SQL映射文件的过程。这个过程可以通过MyBatis提供的逆向工程工具来完成,极大地方便了开发人员,避免了重复的代码编写,提高了开发效率。 创建逆向工程的步骤 1、添加依赖&amp;插件 &lt;!-- 控制Mave
    MyBatis获取参数值的两种方式:${}和#{} ${}的本质就是字符串拼接,#{}的本质就是占位符赋值。 ${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自
    resultMap作用是处理数据表中字段与java实体类中属性的映射关系。 准备工作 ① 创建数据库&amp;数据表 CREATE DATABASE `dbtest1`; CREATE TABLE `t_emp` ( `emp_id` int NOT NULL AUTO_INCREMENT, `em
    EHCache缓存针对于MyBatis的二级缓存。 MyBatis默认二级缓存是SqlSessionFactory级别的。 添加依赖 &lt;!-- MyBatis-EHCache整合包 --&gt; &lt;dependency&gt; &lt;groupId&gt;org.mybatis.cac
    MyBatis 提供了一级缓存和二级缓存的支持,用于提高数据库查询的性能,减少不必要的数据库访问。 一级缓存(SqlSession 级别的缓存) 一级缓存是 MyBatis 中最细粒度的缓存,也称为本地缓存。它存在于每个 SqlSession 的生命周期中,当 SqlSession 被关闭或清空时,
    动态SQL是 MyBatis 中非常强大且灵活的功能,允许你根据不同的条件构建SQL查询。 这主要通过 &lt;if&gt;、&lt;choose&gt;、&lt;when&gt;、&lt;otherwise&gt;、&lt;foreach&gt;等标签实现。 查询场景 /** * 根据条件查询员工
    本教程操作系统:windows10系统、DELL G3电脑。 MyBatis 是一个优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。在 MyBatis 中,配置数据库连接是非常重要的第一步。下面将详细介绍如何配置 MyBatis 的
    今天小编给大家分享的是MyBatis批量查询、插入、更新、删除如何实现,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。
    今天小编给大家分享的是Mybatis操作多数据源实现的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
    本篇文章和大家了解一下mybatis集成到spring的方式有哪些。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。1 前言1.1 集成spring前使用mybat...
    今天小编给大家分享的是mybatis-plus分页查询的3种方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
    本篇内容主要讲解“mybatis之BaseTypeHandler怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“mybatis...
    这篇文章主要介绍了mybatisforeach怎么传两个参数的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇mybatisforeach怎...
    这篇“MyBatis映射文件中parameterType与resultType怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的...
    这篇文章主要介绍“MyBatis怎么获取自动生成的键值”,在日常操作中,相信很多人在MyBatis怎么获取自动生成的键值问题上存在疑惑,小编查阅了各式资料,整理出
    这篇文章主要讲解了“怎么去掉IntelliJIDEA中mybatis对应的xml文件警告”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入...
    这篇文章主要介绍“MybatisPlus使用@TableId主键id自增长无效如何解决”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这...