MyBatis动态SQL怎么实现

发布时间:2022-04-27 13:42:07 作者:iii
来源:亿速云 阅读:133

这篇文章主要介绍了MyBatis动态SQL怎么实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇MyBatis动态SQL怎么实现文章都会有所收获,下面我们一起来看看吧。

mybatis最强大的功能之一便是它的动态sql能力

       借用官方文档的一段话 : 如果您以前有使用JDBC或者类似框架的 经历,您就会明白把SQL语句条件连接在一起是多么的痛苦,要确保不能忘记空格或者不要在 columns列后面省略一个逗号等。动态语句能够完全解决掉这些痛苦。

那么如果没有这种功能到底有多痛苦呢 ? 我们来举例说明

MyBatis动态SQL怎么实现

       这是一张表 , 试想如果我们通过 name 和 age来查询表信息时 , sql语句中肯定会存在 where和and字句 , 但是如果 name或者age 有一个为null或者都为null , 那么此时的 where 和and就会被孤立,那么这样肯定会出现很多问题 , 所以mybatis的动态sql功能帮助我们完美解决

MyBatis 中用于实现动态 SQL 的元素主要有:

If   where   trim   set  choose(when, otherwise)   foreach

if和where

<select id="selectAllEmployee1" resultMap="employeeMap2" parameterType="Employee">
   SELECT e.id,e.name ename,e.age,d.name dname FROM employee e
      LEFT JOIN dept d ON e.deptId = d.id
<where>
    <if test="name!=null &amp; name!=''">
         e.name =#{name}
    </if>
    <if test="age!=null &amp; age!=''">
         and e.age =#{age}
    </if>
</where>
</select>

使用这种标签 , 动态sql可以根据 条件来自动帮我们完善sql 

SqlSession sqlSession= MybatisUtil.getSqlSession();
EmployeeDao mapper=sqlSession.getMapper(EmployeeDao.class);
//创建一个对象,set值
Employee employee = new Employee();
employee.setName("");
employee.setAge(null);
List<Employee> employees = mapper.selectAllEmployee1(employee);
System.out.println(employees);
sqlSession.commit();
sqlSession.close();

第一次我们都设置null值, 表中数据完全被查询

MyBatis动态SQL怎么实现

第二次我们只查询年龄

employee.setName("");
employee.setAge(20);

MyBatis动态SQL怎么实现

查询到两条年龄为20的数据 , 这就是mybatis动态sql的强大之处

trim

上述的 where 与 if 我们也可以使用 trim 来代替where 

<select id="selectAllEmployee1" resultMap="employeeMap2" parameterType="Employee">
     SELECT e.id,e.name ename,e.age,d.name dname FROM employee e
     LEFT JOIN dept d ON e.deptId = d.id
     <trim prefix="where" prefixOverrides="or|and">
        <if test="name!=null &amp; name!=''">
            e.name =#{name}
        </if>
        <if test="age!=null &amp; age!=''">
            and e.age =#{age}
        </if>
     </trim>
</select>

这里有两个属性 prefix , prefixOverrides

prefix : 代表前缀 , 如果if 中有成立的条件, 就会在sql前面拼入where字句

prefixOverrides :  根据if 条件自动判断是否去除 or | and字句

相应的也有suffix与suffixOverrides , 代表对尾部的判断

Choose

choose代表多路选择(多选一)

<select id="selectAllEmployee1" resultMap="employeeMap2" parameterType="Employee">
        SELECT e.id,e.name ename,e.age,d.name dname FROM employee e
        LEFT JOIN dept d ON e.deptId = d.id
        <trim prefix="where" prefixOverrides="or|and">
            <choose>
                <when test="name!=null &amp; name!=''">
                    and e.name =#{name}
                </when>
                <when test="age!=null">
                    and e.age =#{age}
                </when>
                <otherwise>
                    and e.name ='李雷'
                </otherwise>
            </choose>
        </trim>
    </select>

当<when>中的条件成立时, 走when中的语句,都不成立走<otherwise>

Set

set 可以根据条件自动添加set字句,动态更新列,也可以来剔除追加到条件末尾的任何不相关的逗号

<update id="updateEmployee">
        update employee
        <set>
            <if test="name!=null &amp; name!=''">
                name=#{name},
            </if>
            <if test="age!=null">
                age=#{age},
            </if>
        </set>
        where id=#{id}
    </update>

foreach

       <foreach> 主要用在构建 in 条件中,它可以在 SQL 语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。 item 表示集合中每一个元素进行迭代时的别名,index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open 表示该语句以什么开始, separator 表示在每次进行迭代之间以什么符号作为分隔符,close 表示以什么结束,在使用 foreach 的时候最关键的也是最容易出错的就是 collection 属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的。

&ndash; 如果传入的是单参数且参数类型是一个 List 的时候,collection 属 性值为 list

&ndash; 如果传入的是单参数且参数类型是一个 array 数组的时候, collection 的属性值为array

//创建一个list集合
List<Integer> list = new ArrayList<>();
list.add(19);
list.add(20);
List<Employee> employees = mapper.selectAllEmployee2(list);

接口方法如下 : 

  List<Employee> selectAllEmployee2(List<Integer> list);

对应动态sql如下 : 

<select id="selectAllEmployee2" resultMap="employeeMap2" parameterType="Employee">
        SELECT e.id,e.name ename,e.age,d.name dname FROM employee e
        LEFT JOIN dept d ON e.deptId = d.id where age in
        <foreach collection="list" item="age" open="(" separator="," close=")">
             #{age}
        </foreach>
    </select>

这里我们传入的是一个集合, 所以参数选择 list , 通过foreach我们可以动态的根据集合里的值来查询

关于“MyBatis动态SQL怎么实现”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“MyBatis动态SQL怎么实现”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. MyBatis动态sql
  2. 如何在MyBatis中实现动态SQL

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis sql

上一篇:python中的asyncio异步协程怎么实现

下一篇:JetBrains迭代循环模板快捷键实例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》