动态SQL:

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,
它存在的意义是:"为了解决拼接SQL语句字符串时的痛点问题"。

一、If

  • if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行

  • 在where后面添加一个恒成立条件1=1

    • 这个恒成立条件并不会影响查询的结果

    • 这个1=1可以用来拼接and语句,例如:当empName为null时

      • 如果不加上恒成立条件,则SQL语句为select * from t_emp where and age = ? and sex = ? and email = ?,此时where会与and连用,SQL语句会报错

      • 如果加上一个恒成立条件,则SQL语句为select * from t_emp where 1= 1 and age = ? and sex = ? and email = ?,此时不报错

public interface DynamicMapper {
/**
* 动态sql,if语句
* @param emp
* @return
*/
List<Emp> getEmpByCondition(Emp emp);
}
 <!--List<Emp> getEmpByCondition(Emp emp);-->
<!-- and == && ,所以条件都要满足 -->
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp where 1=1
<if test="empName != null and empName !=''">
and emp_name = #{empName}
</if>
<if test="age != null and age !=''">
and age = #{age}
</if>
<if test="sex != null and sex !=''">
and sex = #{sex}
</if>
<if test="email != null and email !=''">
and email = #{email}
</if>
</select>
 @Test
public void testGetEmpByCondition() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
DynamicMapper mapper = sqlSession.getMapper(DynamicMapper.class);
List<Emp> empByCondition = mapper.getEmpByCondition(new Emp(null,"王五",34,"女","423423"));
System.err.println(empByCondition);
sqlSession.close();
// empName='王五', age=34, sex='女', email='423423'
}

二、where

  • where和if一般结合使用:

    • 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字

    • 若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最 "前方" 多余的and/or去掉

 /**
* 动态sql,where
* @param emp
* @return
*/
List<Emp> getEmpByCondition_where(Emp emp);
<!--List<Emp> getEmpByCondition_where(Emp emp);-->
<select id="getEmpByCondition_where" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName !=''">
and emp_name = #{empName}
</if>
<if test="age != null and age !=''">
and age = #{age}
</if>
<if test="sex != null and sex !=''">
and sex = #{sex}
</if>
<if test="email != null and email !=''">
and email = #{email}
</if>
</where>
</select>
@Test //where
public void testGetEmpByCondition_were() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
DynamicMapper mapper = sqlSession.getMapper(DynamicMapper.class);
List<Emp> empByCondition = mapper.getEmpByCondition_where(new Emp(null, "王五", 34, "女", "423423"));
System.err.println(empByCondition);
sqlSession.close();
// empName='王五', age=34, sex='女', email='423423'
}

错误示范:where标签不能去掉 "条件后" 多余的and/or

<!--这种用法是错误的,只能去掉条件前面的and/or,条件后面的不行-->
<if test="empName != null and empName !=''">
emp_name = #{empName} and
</if>
<if test="age != null and age !=''">
age = #{age}
</if>

三、trim

  • trim用于去掉或添加标签中的内容

  • 常用属性

    • prefix:在trim标签中的内容的 {"前面添加"} - 某些内容

    • suffix:在trim标签中的内容的{"后面添加"} 某些内容

    • prefixOverrides:在trim标签中的内容的 {"前面去掉某"} 些内容

    • suffixOverrides:在trim标签中的内容的 {"后面去掉某"} 些内容

  • 若trim中的标签都不满足条件,则trim标签没有任何效果,也就是只剩下select * from t_emp

 /**
* 动态sql,trim
* @param emp
* @return
*/
List<Emp> getEmpByCondition_trim(Emp emp);
 <!--List<Emp> getEmpByCondition_trim(Emp emp);-->
<select id="getEmpByCondition_trim" resultType="Emp">
select * 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} and
</if>
<if test="sex != null and sex !=''">
sex = #{sex} or
</if>
<if test="email != null and email !=''">
email = #{email}
</if>
</trim>
</select>
 @Test //trim
public void testGetEmpByCondition_trim() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
DynamicMapper mapper = sqlSession.getMapper(DynamicMapper.class);
List<Emp> empByCondition = mapper.getEmpByCondition_trim(new Emp(null, "王五", 34, "女", "423423"));
System.err.println(empByCondition);
sqlSession.close();
// empName='王五', age=34, sex='女', email='423423'
}

四、choose、when、otherwise

  • "choose、when、otherwise" 相当于 "if...else if..else"

  • when至少要有一个,otherwise至多只有一个

/**
* 动态sql,choose、when、otherwise
* @param emp
* @return
*/
List<Emp> getEmpByCondition_choose(Emp emp);
<!--    List<Emp> getEmpByCondition_choose(Emp emp);-->
<select id="getEmpByCondition_choose" resultType="Emp">
select * from t_emp
<where>
<choose>
<!--当一个when执行了一个,剩下就不会执行。因为他们是if...else if..else-->
<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 //choose
public void testGetEmpByCondition_choose() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
DynamicMapper mapper = sqlSession.getMapper(DynamicMapper.class);
List<Emp> empByCondition = mapper.getEmpByCondition_choose(new Emp(null, "王五", 34, "女", "423423"));
System.err.println(empByCondition);
sqlSession.close();
// empName='王五', age=34, sex='女', email='423423'
}

解析:

五、foreach

  • 属性:

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

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

    • separator:设置循环体之间的分隔符,分隔符前后默认有一个空格,如,

    • open:设置foreach标签中的内容的开始符

    • close:设置foreach标签中的内容的结束符

  • 5.1-批量删除:

/**
* 动态sql,"foreach-实现批量删除"
* @param eids
* @return
*/
Integer deleteMoreByArray(@Param("eids") Integer[] eids);
// 删除的SQL:DELETE  FROM  t_emp where eid IN (9,10)

  <!--Integer deleteMoreByArray(@Param("eids") Integer[] eids);-->
<!--SQL:DELETE FROM t_emp where eid IN (9,10)-->
<delete id="deleteMoreByArray">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
@Test //foreach-批量删除
public void testDeleteMoreByArray() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
DynamicMapper mapper = sqlSession.getMapper(DynamicMapper.class);
Integer integer = mapper.deleteMoreByArray(new Integer[]{7, 8});
System.err.println("受影响的行数:" + integer);
sqlSession.close();
}
  • 5.2-批量增加:

/**
* 动态sql,"foreach-实现批量增加"
* @param emps
* @return
*/
Integer insertMoreByList(@Param("emps") List<Emp> emps);
//批量添加的SQL语句:insert into t_emp values (null,"a",23,"男","321412@111",NULL),(null,"a1",23,"男","321412@111",NULL) 

<!--    Integer 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>
@Test
public void insertMoreByList() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
DynamicMapper mapper = sqlSession.getMapper(DynamicMapper.class);
Emp emp1 = new Emp(null, "a", 13, "人妖", "2412343@qq.com");
Emp emp2 = new Emp(null, "b", 1, "男", "123@321.com");
Emp emp3 = new Emp(null, "c", 1, "男", "123@321.com");
List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
int result = mapper.insertMoreByList(emps);
System.out.println(result);
}

六、SQL片段:

  • ql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

  • 声明sql片段:标签

<sql id="empColumns">eid,emp_name,age,sex,email</sql>
  • 引用sql片段:标签

<sql id="empColumns">eid,emp_name,age,sex,email</sql><!--sql片段-->

    <!--List<Emp> getEmpByCondition(Emp emp);-->
<!-- and == && ,所以条件都要满足 -->
<select id="getEmpByCondition_if" resultType="Emp">
select <include refid="empColumns"></include> from t_emp where 1=1
<if test="empName != null and empName !=''">
and emp_name = #{empName}
</if>
<if test="age != null and age !=''">
and age = #{age}
</if>
<if test="sex != null and sex !=''">
and sex = #{sex}
</if>
<if test="email != null and email !=''">
and email = #{email}
</if>
</select>

MyBatis_07(动态SQL)的更多相关文章

  1. 值得注意的ibatis动态sql语法格式

    一.Ibatis常用动态sql语法,简单粗暴用一例子 <select id="iBatisSelectList" parameterClass="java.util ...

  2. Mysql - 游标/动态sql/事务

    游标这个在我目前的项目里面用的还不多, 但是其功能还是很强大的. 动态sql以前都没用过, 是跟着富士康(不是张全蛋的富土康哦)过来的同事学的. 还是挺好用的. 我的数据库方面, 跟他学了不少. 在此 ...

  3. MyBatis4:动态SQL

    什么是动态SQL MyBatis的一个强大特性之一通常是它的动态SQL能力.如果你有使用JDBC或其他相似框架的经验,你就明白条件串联SQL字符串在一起是多么地痛苦,确保不能忘了空格或者在列表的最后的 ...

  4. 分享公司DAO层动态SQL的一些封装

    主题 公司在DAO层使用的框架是Spring Data JPA,这个框架很好用,基本不需要自己写SQL或者HQL就能完成大部分事情,但是偶尔有一些复杂的查询还是需要自己手写原生的Native SQL或 ...

  5. MySQL存储过程动态SQL语句的生成

    用Mysql存储过程来完成动态SQL语句,使用存储过程有很好的执行效率: 现在有要求如下:根据输入的年份.国家.节假日类型查询一个节假日,我们可以使用一般的SQL语句嵌入到Java代码中,但是执行效率 ...

  6. 【Java EE 学习 79 下】【动态SQL】【mybatis和spring的整合】

    一.动态SQL 什么是动态SQL,就是在不同的条件下,sql语句不相同的意思,曾经在“酒店会员管理系统”中写过大量的多条件查询,那是在SSH的环境中,所以只能在代码中进行判断,以下是其中一个多条件查询 ...

  7. 自定义函数执行动态sql语句

    --函数中不能调用动态SQL,使用用存储过程吧.如果还要对函数做其他操作,换成存储过程不方便,可以考虑把其他操作一起封装在存储过程里面.如:   create proc [dbo].[FUN_YSCL ...

  8. mybatis入门基础(五)----动态SQL

    一:动态SQL 1.1.定义 mybatis核心对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接.组装. 1.2.案例需求 用户信息综合查询列表这个statement的定义使用动态s ...

  9. mybatis 动态sql表达式相关应用

    一.mybatis 表达式简介 对于mybatis3 ,提供了一种动态sql的方式.通过动态sql我们可以直接在mybatis 的xm映射文件中直接通过条件判断的方式进行查询添加的拼接.mybatis ...

  10. (转)Mybatis高级映射、动态SQL及获得自增主键

    原文:http://www.cnblogs.com/edwinchen/p/4105278.html?utm_source=tuicool&utm_medium=referral 一.动态SQ ...

随机推荐

  1. sql注入关键字

    id=inurl:Produit.php?id=inurl:Profile_view.php?id=inurl:Publications.php?id=inurl:Stray-Questions-Vi ...

  2. vue-cli框架的下载以及框架目录介绍

    目录 vue-cli框架的下载以及框架目录介绍 一.vue-cli创建项目 二.Vue项目目录介绍 vue-cli框架的下载以及框架目录介绍 一.vue-cli创建项目 在终端下载先下载cnpm # ...

  3. (三) MdbCluster分布式内存数据库——节点状态变化及分片调整

    (三) MdbCluster分布式内存数据库--节点状态变化及分片调整   上一篇: (二) MdbCluster分布式内存数据库--分布式架构   昨天我们在测试节点动态扩缩容时,发现了一个小bug ...

  4. xampp修改mysql数据库密码(测试成功)

    转载: http://www.360doc.com/content/17/0608/14/8797027_661063783.shtml ------------------------------- ...

  5. Linux提权之:利用capabilities提权

    Linux提权之:利用capabilities提权 目录 Linux提权之:利用capabilities提权 1 背景 2 Capabilities机制 3 线程与文件的capabilities 3. ...

  6. ElasticSearch 实现分词全文检索 - 概述

    需求 做一个类似百度的全文搜索功能 所用的技术如下: ElasticSearch Kibana 管理界面 IK Analysis 分词器 SpringBoot ElasticSearch 简介 ES ...

  7. Day 13 13.2 requests之请求参数与请求体

    请求参数与请求体参数 一.什么是params参数(请求参数) get 方法是可以向服务器发送信息的,除了可以请求需要的页面之外,也可以发送我们指定的内容,这就是通过 params 参数实现的 requ ...

  8. Linux修改开机图形/etc/motd

    修改 /etc/motd vim /etc/motd 植入图形 .--, .--, ( ( \.---./ ) ) '.__/o o\__.' {= ^ =} > - < / \ // \ ...

  9. Lnmp切换PHP版本

    进入lnmp的安装目录 cd /root/lnmp1.8 执行 ./install.sh mphp 然后选择你要变更的版本

  10. Cannot read properties of null (reading ‘insertBefore‘)

    一.报错现象 vue3 + element plus 项目,本地启动时,页面进行所有操作都正常:部署到test环境后,数据驱动DOM变化的操作会导致如下报错. 二.可能原因及解决方案 经过分析出现报错 ...