动态SQL语句是核心之一,这里我们通过几个示例来演示

一 多条件查询专题

1.通过恒等式完成动态SQL语句

涉及到if标签

<mapper namespace="com.shxt.model.User"><resultMap type="com.shxt.model.User" id="BaseResultMapper"><id column="user_id" property="user_id" /><result column="user_name" property="user_name" /><result column="sex" property="sex" /><result column="money" property="money" /><result column="birthday" property="birthday" /></resultMap><sql id="oa_user_columns">user_id,user_name,sex,money,birthday</sql><sql id="oa_user_columns_alias">${alias}.user_id,${alias}.user_name,${alias}.sex,${alias}.money,${alias}.birthday</sql>
</mapper>
  • 映射文件
    <!-- 1.姓名和性别的条件查询 --><!-- A.通过恒等式完成动态SQL语句 --><select id="if01" parameterType="map" resultMap="BaseResultMapper">SELECT<include refid="oa_user_columns" />FROMoa_userWHERE 1=1<if test="name != null && name != ''">AND user_name LIKE CONCAT('%',#{name},'%')</if><if test="sex != null and sex != ''">AND sex=#{sex}</if></select>
  • Java测试代码
    @Testpublic void IF标签01(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();Map<String,Object> query = new HashMap<>();query.put("name", "悟");query.put("sex", "男");List<User> userList =sqlSession.selectList(User.class.getName()+".if01", query);System.out.println(userList);} finally {MyBatisUtils.closeSqlSession(sqlSession);}}
  • 图解说明

2.where标签和if标签组合

  • 如果发现标签內有内容,那么会在内容的最前面加入关键字 where
  • 如果有内容,会检查内容的最前面是否含有 AND空格 或者 OR空格 ,自动将其抹掉
  • 映射文件
    <!-- B.推荐方式 WHERE标签 --><select id="if02" parameterType="map" resultMap="BaseResultMapper">SELECT<include refid="oa_user_columns" />FROMoa_user<where><if test="name != null && name != ''">AND      user_name LIKE CONCAT('%',#{name},'%')</if><if test="sex != null and sex != ''">AND sex=#{sex}</if></where></select>
  • Java测试代码
    @Testpublic void IF标签02(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();Map<String,Object> query = new HashMap<>();query.put("name", "悟");query.put("sex", "男");List<User> userList =sqlSession.selectList(User.class.getName()+".if02", query);System.out.println(userList);} finally {MyBatisUtils.closeSqlSession(sqlSession);}}
  • 图解说明

3.trim标签和if标签

<trimprefix="当发现有内容的时候,你在内容的最前面想加入什么内容"prefixOverrides="当发现有内容的时候,你在内容的最前面想抹掉什么内容"suffix="当发现有内容的时候,你在内容的最后面面想加入什么内容"suffixOverrides="当发现有内容的时候,你在内容的最后面想抹掉什么内容">
</trim>
  • 映射文件
     <!-- C.trim标签 --><select id="if03" parameterType="map" resultMap="BaseResultMapper">SELECT<include refid="oa_user_columns" />FROMoa_user<trim prefix="WHERE " prefixOverrides="AND |OR "><if test="name != null && name != ''">AND user_name LIKE CONCAT('%',#{name},'%')</if><if test="sex != null and sex != ''">AND sex=#{sex}</if></trim></select>
  • Java测试代码
    @Testpublic void trim标签(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();Map<String,Object> query = new HashMap<>();query.put("name", "悟");query.put("sex", "男");List<User> userList =sqlSession.selectList(User.class.getName()+".if03", query);System.out.println(userList);} finally {MyBatisUtils.closeSqlSession(sqlSession);}}
  • 图解说明

二 更新操作

1.set标签

  • 当你发现有内容的时候,在内容的最前面加入 set
  • 当你发现有内容的时候,检查内容的最后面是否有逗号"," 如果将其抹掉
  • 映射文件
    <update id="update01" parameterType="com.shxt.model.User">UPDATEoa_user<set><if test="user_name != null and user_name != ''">user_name=#{user_name},</if><if test="sex != null and sex != ''">sex=#{sex},</if><if test="money != null">money=#{money},</if><if test="birthday != null">birthday=#{birthday},</if></set>WHEREuser_id=#{user_id}</update>
  • Java测试代码
    @Testpublic void 更新操作_变更数据库(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();//数据User user = new User();user.setUser_id(3);user.setUser_name("天蓬元帅");//日期的转换String date = "1998-09-09";DateFormat df = new SimpleDateFormat("yyyy-MM-dd");user.setBirthday(df.parse(date));int row =sqlSession.update(User.class.getName()+".update01", user);System.out.println(row);//事务的提交sqlSession.commit();}catch (Exception ex) {ex.printStackTrace();}finally {MyBatisUtils.closeSqlSession(sqlSession);}}
  • 图解说明

2.trim标签完成更新

  • 映射文件
    <update id="update02" parameterType="com.shxt.model.User">UPDATEoa_user<trim prefix="SET " suffixOverrides=","><if test="user_name != null and user_name != ''">user_name=#{user_name},</if><if test="sex != null and sex != ''">sex=#{sex},</if><if test="money != null">money=#{money},</if><if test="birthday != null">birthday=#{birthday},</if></trim>WHEREuser_id=#{user_id}</update>
  • Java测试代码
    @Testpublic void 更新操作_TRIM标签_变更数据库(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();//数据User user = new User();user.setUser_id(3);user.setUser_name("天蓬元帅123");//日期的转换String date = "1998-10-09";DateFormat df = new SimpleDateFormat("yyyy-MM-dd");user.setBirthday(df.parse(date));int row =sqlSession.update(User.class.getName()+".update02", user);System.out.println(row);//事务的提交sqlSession.commit();}catch (Exception ex) {ex.printStackTrace();}finally {MyBatisUtils.closeSqlSession(sqlSession);}}

三 choose 标签简单使用

  • 映射文件
    <select id="choose01" parameterType="map" resultMap="BaseResultMapper">SELECT<include refid="oa_user_columns"/>FROMoa_userWHERE<choose><when test='sex != null and sex=="男"'>money>777</when><when test='sex != null and sex=="女"'>money>666</when><otherwise>1=1</otherwise></choose></select>
  • Java测试代码
    @Testpublic void choose标签(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();Map<String,Object> query = new HashMap<>();query.put("sex", "女123213");List<User> userList =sqlSession.selectList(User.class.getName()+".choose01", query);System.out.println(userList);} finally {MyBatisUtils.closeSqlSession(sqlSession);}}

四 小于号问题

  • 映射文件
    <select id="less01" parameterType="double" resultMap="BaseResultMapper">SELECT<include refid="oa_user_columns"/>FROM oa_userWHEREmoney <= #{money}</select><select id="less02" parameterType="double" resultMap="BaseResultMapper">SELECT<include refid="oa_user_columns"/>FROM oa_userWHERE<!-- 里面不能包含标签 --><![CDATA[money <= #{money}]]></select>
  • Java测试代码
    @Testpublic void 小于号的解决问题(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();List<User> userList =sqlSession.selectList(User.class.getName()+".less01", 1.0*800);System.out.println(userList);userList =sqlSession.selectList(User.class.getName()+".less02",  1.0*600);System.out.println(userList);} finally {MyBatisUtils.closeSqlSession(sqlSession);}}
  • 图解说明

请参考附录1说明

五 动态添加语句

  • 映射文件
    <insert id="add01" parameterType="com.shxt.model.User"useGeneratedKeys="true" keyProperty="user_id">INSERT INTO oa_user<trim prefix="(" suffix=")" suffixOverrides=","><if test="user_name != null and user_name!=''">user_name,</if><if test="sex != null and sex!=''">sex,</if><if test="money != null">money,</if><if test="birthday != null">birthday,</if></trim><trim prefix="VALUES (" suffix=")" suffixOverrides=","><if test="user_name != null and user_name!=''">#{user_name},</if><if test="sex != null and sex!=''">#{sex},</if><if test="money != null">#{money},</if><if test="birthday != null">#{birthday},</if></trim></insert>
  • Java测试代码
    @Testpublic void 动态的添加语句(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();//数据User user = new User();user.setUser_name("刘备12333333");//日期的转换String date = "1998-10-09";DateFormat df = new SimpleDateFormat("yyyy-MM-dd");user.setBirthday(df.parse(date));user.setMoney(1111.11);int row =sqlSession.insert(User.class.getName()+".add01", user);System.out.println(row);//事务的提交sqlSession.commit();System.out.println(user);}catch (Exception ex) {ex.printStackTrace();}finally {MyBatisUtils.closeSqlSession(sqlSession);}}

六 foreach标签

1.数组方式

  • 映射方式
    <!-- 数组删除,如果数组的话,请不要去设置paramterType,让其自动识别 --><delete id="delete01" >DELETE FROMoa_userWHERE user_id in <!-- 对数组进行遍历 如果你只是传了一个数组或者一个集合collection="array|list"--><foreach collection="array" item="shxt"open="(" close=")" separator=",">#{shxt}</foreach></delete>
  • Java测试代码
    @Testpublic void 传递数组删除规则(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();int row = sqlSession.delete(User.class.getName()+".delete01", new int[]{5,6});//事务的提交sqlSession.commit();System.out.println(row);}catch (Exception ex) {ex.printStackTrace();}finally {MyBatisUtils.closeSqlSession(sqlSession);}}

2.List方式

  • 映射文件
     <!-- List集合 --><delete id="delete02" parameterType="list">DELETE FROMoa_userWHERE user_id in <foreach collection="list" item="shxt"open="(" close=")" separator=",">#{shxt}</foreach></delete>
  • Java测试代码
    @Testpublic void 传递集合删除规则(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();List<Integer> tempList = new ArrayList<>();tempList.add(8);tempList.add(9);int row = sqlSession.delete(User.class.getName()+".delete02", tempList);//事务的提交sqlSession.commit();System.out.println(row);}catch (Exception ex) {ex.printStackTrace();}finally {MyBatisUtils.closeSqlSession(sqlSession);}}

3.Map方式

  • 映射方式
    <delete id="delete03" parameterType="map">DELETE FROMoa_userWHERE user_id in <foreach collection="id_array" item="shxt"open="(" close=")" separator=",">#{shxt}</foreach></delete>
  • Java测试代码
    @Testpublic void 传递Map删除规则(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.getSqlSession();List<Integer> tempList = new ArrayList<>();tempList.add(7);tempList.add(10);Map<String, Object> map = new HashMap<String, Object>();map.put("id_array", tempList);int row = sqlSession.delete(User.class.getName()+".delete03", map);//事务的提交sqlSession.commit();System.out.println(row);}catch (Exception ex) {ex.printStackTrace();}finally {MyBatisUtils.closeSqlSession(sqlSession);}}
  • 图解方式

4.批量添加

  • 映射文件
    <insert id="add02" parameterType="list">INSERT INTOoa_userVALUES<foreach collection="list" item="user" separator=",">(#{user.user_name},#{user.sex},#{user.money})</foreach></insert>

附录1 : MyBatis在xml文件中处理大于号小于号的方法

第一种方法:

用了转义字符把>和<替换掉,然后就没有问题了。

SELECT * FROM test WHERE 1 = 1 AND start_date  <= CURRENT_DATE AND end_date >= CURRENT_DATE

附:XML转义字符

第二种方法

因为这个是xml格式的,所以不允许出现类似“>”这样的字符,但是都可以使用<![CDATA[ ]]>符号进行说明,将此类符号不进行解析
你的可以写成这个:
mapper文件示例代码

<![CDATA[ when min(starttime)<='12:00' and max(endtime)<='12:00' ]]>  

7.平凡之路-动态SQL语句相关推荐

  1. Oracle基础 动态SQL语句

    一.静态SQL和动态SQL的概念. 1.静态SQL 静态SQL是我们常用的使用SQL语句的方式,就是编写PL/SQL时,SQL语句已经编写好了.因为静态SQL是在编写程序时就确定了,我们只能使用SQL ...

  2. 动态SQL语句--mybatis

    转自:http://www.blogjava.net/Steven-bot/articles/363460.html 动态SQL语句--mybatis 动态SQL语句         有些时候,sql ...

  3. oracle中执行动态sql语句吗,oracle中有没有可动态执行sql语句的函数

    oracle中有没有可动态执行sql语句的函数 关注:233  答案:2  手机版 解决时间 2021-03-05 15:53 提问者祗剩寂寞 2021-03-04 22:38 oracle中有没有可 ...

  4. Mybatis Plus 是如何实现动态 SQL 语句的?原理你懂吗?

    作者 | 稻草江南 来源 | https://juejin.cn/post/6883081187103866894 Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,那么它是怎么 ...

  5. Sql Server实用操作-动态sql语句基本语法

    如何将exec执行结果放入变量中? declare @num int, @sqls nvarchar(4000) set @sqls='select @a=count(*) from tableNam ...

  6. IBatis.net动态SQL语句

    在学习动态SQL语句之前,首先必须对条件查询有一定了解,先来学习如何向IBatis.Net的映射文件里传入参数. 一.条件查询 1.传递单个参数 如根据Id查询: <select id=&quo ...

  7. Mybatis映射文件动态SQL语句-01

    因为在很多业务逻辑复杂的项目中,往往不是简单的sql语句就能查询出来自己想要的数据,所有mybatis引入了动态sql语句, UserMapper.xml <?xml version=" ...

  8. MyBatis——动态SQL语句——if标签和where标签复合使用

    功能需求 根据性别和名字查询用户 官方文档 MyBatis--动态 SQL SQL语句 SELECT id, username, birthday, sex, address FROM `user` ...

  9. oracle不使用游标,oracle – 为什么我们不能在动态SQL语句中使用强引用游标?

    这是一个带有强类型引用游标的过程: SQL> create or replace procedure p1 is 2 type dept_rc is ref cursor return dept ...

最新文章

  1. PHP程序员突破成长瓶颈
  2. 安装apache+gd2(jpeg,png等)+mysql-client+php脚本
  3. element ui点击按钮弹出款_前端猿应该知道的十大最流行的前端UI框架
  4. LeetCode 题解之Add Two Numbers II
  5. 初步认识Volatile-JMM
  6. eclipse启动速度等优化设置
  7. 毕业后拉开距离的真正原因!
  8. Sql: 去除字符串中的相同的字符串函數
  9. 【Python】基于Python的百度迁徙4——上班和休闲指数(附代码)
  10. higtech软件的使用
  11. 武汉理工大学-数值分析-2019年期末复习提纲
  12. c#(WinForm)绘制两个圆的内公切线
  13. Win10下双系统Ubuntu14.04+GTX1070+CUDAcuDNN+Tensorflow环境搭建
  14. c语言中y=0x20什么意思,0x20(十六进制0x20等于多少)
  15. Java项目:SSM实现的一个在线文具学习用品购买商城网站
  16. 独享带宽和共享带宽有哪些区别?
  17. 老毛桃制作装机版u盘
  18. 新媒体运营:2019年微信改版,裂变增长如何做? 黎想
  19. java计算机毕业设计手机测试管理系统源代码+数据库+系统+lw文档
  20. 石头机器人红灯快闪_5.1南宁上演“科幻大片”!各闹市街头惊现“机器人快闪”...

热门文章

  1. 写一个登录页面,输入用户名密码, 如果输入正确,跳转 欢迎页面输入错误,返回登录页面,提示错误
  2. 分类算法-KNN(原理+代码+结果)
  3. CUDA学习(九):共享内存
  4. 2019年各大顶会神经关系抽取(NRE)优质论文整理分享
  5. python 按姓名排序excel
  6. 你们还记得张江男、张江女两张图片吗?-装饰模式
  7. linux编译ffmpeg(一)
  8. Python异步爬虫之协程抓取妹子图片(aiohttp、aiofiles)
  9. 专访阿里云AI科学家闵万里:AI试水电力调度是道让人兴奋的题目
  10. 见微知著,以小“控”大的三极管(四)