mybatis动态SQL语句

三、动态SQL语句

        有些时候,sql语句where条件中,需要一些安全判断,例如按性别检索,如果传入的参数是空的,此时查询出的结果很可能是空的,也许我们需要参数为空时,是查出全部的信息。这是我们可以使用动态sql,增加一个判断,当参数不符合要求的时候,我们可以不去判断此查询条件。
        下文均采用mysql语法和函数(例如字符串链接函数CONCAT)。

1 if标签

<!-- 查询学生list,like姓名 -->  
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST    
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   
</select>

<!-- 查询学生list,like姓名 -->  
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST   
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
</select>  

但是此时如果studentName是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。

修改为:

<!-- 查询学生list,like姓名 -->  
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST   <if test="studentName!=null and studentName!='' ">  WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   </if>  
</select> 

<!-- 查询学生list,like姓名 -->  
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST  <if test="studentName!=null and studentName!='' ">  WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  </if>  
</select>  

 此时,当studentName的值为null或’’的时候,我们并不进行where条件的判断,所以当studentName值为null或’’值,不附带这个条件,所以查询结果是全部。

 由于参数是Java的实体类,所以我们可以把所有条件都附加上,使用时比较灵活, new一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会where这个条件,相反不去赋值就可以不在where中判断。

<!-- 查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 -->  
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST   <where>  <if test="studentName!=null and studentName!='' ">  ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   </if>  <if test="studentSex!= null and studentSex!= '' ">  AND ST.STUDENT_SEX = #{studentSex}   </if>  <if test="studentBirthday!=null">  AND ST.STUDENT_BIRTHDAY = #{studentBirthday}   </if>  <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">  AND ST.CLASS_ID = #{classEntity.classID}   </if>  </where>  
</select>  

2 where、set、trim标签

2.1 where

   当if标签较多时,这样的组合可能会导致错误。例如,like姓名,等于指定性别等:

  1. <!-- 查询学生list,like姓名,=性别 -->  
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST   
  4.         WHERE   
  5.         <if test="studentName!=null and studentName!='' ">  
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   
  7.         </if>  
  8.         <if test="studentSex!= null and studentSex!= '' ">  
  9.             AND ST.STUDENT_SEX = #{studentSex}   
  10.         </if>  
  11. </select>  

如果上面例子,参数studentName为null或’’,则或导致此sql组合成“WHERE AND”之类的关键字多余的错误SQL。
 这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
 上面例子修改为:

Xml代码 复制代码 收藏代码
<!-- 查询学生list,like姓名,=性别 -->  
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST   <where>  <if test="studentName!=null and studentName!='' ">  ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   </if>  <if test="studentSex!= null and studentSex!= '' ">  AND ST.STUDENT_SEX = #{studentSex}   </if>  </where>  
</select>  

2.2 set

当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
没有使用if标签时,如果有一个参数为null,都会导致错误,如下示例:

<!-- 更新学生信息 -->  
<update id="updateStudent" parameterType="StudentEntity">  UPDATE STUDENT_TBL   SET STUDENT_TBL.STUDENT_NAME = #{studentName},   STUDENT_TBL.STUDENT_SEX = #{studentSex},   STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},   STUDENT_TBL.CLASS_ID = #{classEntity.classID}   WHERE STUDENT_TBL.STUDENT_ID = #{studentID};   
</update> 

使用set+if标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:

<!-- 更新学生信息 -->  
<update id="updateStudent" parameterType="StudentEntity">  UPDATE STUDENT_TBL   <set>  <if test="studentName!=null and studentName!='' ">  STUDENT_TBL.STUDENT_NAME = #{studentName},   </if>  <if test="studentSex!=null and studentSex!='' ">  STUDENT_TBL.STUDENT_SEX = #{studentSex},   </if>  <if test="studentBirthday!=null ">  STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},   </if>  <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">  STUDENT_TBL.CLASS_ID = #{classEntity.classID}   </if>  </set>  WHERE STUDENT_TBL.STUDENT_ID = #{studentID};   
</update>

2.3 trim

 trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。


 where例子的等效trim语句:

<!-- 查询学生list,like姓名,=性别 -->  
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST   <trim prefix="WHERE" prefixOverrides="AND|OR">  <if test="studentName!=null and studentName!='' ">  ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   </if>  <if test="studentSex!= null and studentSex!= '' ">  AND ST.STUDENT_SEX = #{studentSex}   </if>  </trim>  
</select>  

set例子的等效trim语句:

<!-- 更新学生信息 -->  
<update id="updateStudent" parameterType="StudentEntity">  UPDATE STUDENT_TBL   <trim prefix="SET" suffixOverrides=",">  <if test="studentName!=null and studentName!='' ">  STUDENT_TBL.STUDENT_NAME = #{studentName},   </if>  <if test="studentSex!=null and studentSex!='' ">  STUDENT_TBL.STUDENT_SEX = #{studentSex},   </if>  <if test="studentBirthday!=null ">  STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},   </if>  <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">  STUDENT_TBL.CLASS_ID = #{classEntity.classID}   </if>  </trim>  WHERE STUDENT_TBL.STUDENT_ID = #{studentID};   
</update> 

3 choose (when, otherwise)

         有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。
         if是与(and)的关系,而choose是或(or)的关系。


         例如下面例子,同样把所有可以限制的条件都写上,方面使用。选择条件顺序,when标签的从上到下的书写顺序:

<!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose -->  
<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">  SELECT * from STUDENT_TBL ST   <where>  <choose>  <when test="studentName!=null and studentName!='' ">  ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   </when>  <when test="studentSex!= null and studentSex!= '' ">  AND ST.STUDENT_SEX = #{studentSex}   </when>  <when test="studentBirthday!=null">  AND ST.STUDENT_BIRTHDAY = #{studentBirthday}   </when>  <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">  AND ST.CLASS_ID = #{classEntity.classID}   </when>  <otherwise>  </otherwise>  </choose>  </where>  
</select>  

4 foreach

对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。
List 实例将使用“list”做为键,数组实例以“array” 做为键。

foreach属性

属性描述
item 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
具体说明:在list和数组中是其中的对象,在map中是value。
该参数为必选。
collection 要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象没有默认的键
当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
如果User有属性List ids。入参是User对象,那么这个collection = "ids"
如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
上面只是举例,具体collection等于什么,就看你想对那个元素做循环。
该参数为必选。
separator 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
open foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
close foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
index 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。

4.1参数为list实例的写法:

SQL写法:

<select id="getStudentListByClassIDs" resultMap="studentResultMap">  SELECT * FROM STUDENT_TBL ST   WHERE ST.CLASS_ID IN    <foreach collection="list" item="classList"  open="(" separator="," close=")">  #{classList}   </foreach>      
</select> 

接口的方法声明:

  1. public List<StudentEntity> getStudentListByClassIDs(List<String> classList);  


  1. List<String> classList = new ArrayList<String>();   
  2. classList.add("20000002");   
  3. classList.add("20000003");   
  4.   
  5. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);   
  6. for( StudentEntity entityTemp : studentList){   
  7.     System.out.println(entityTemp.toString());   

4.2参数为Array实例的写法:

 

SQL语句:

<select id="getStudentListByClassIDs" resultMap="studentResultMap">  SELECT * FROM STUDENT_TBL ST   WHERE ST.CLASS_ID IN    <foreach collection="array" item="ids"  open="(" separator="," close=")">  #{ids}   </foreach>  
</select> 

 接口的方法声明:

Java代码 复制代码 收藏代码
  1. public List<StudentEntity> getStudentListByClassIDs(String[] ids);  

测试代码,查询学生中,在20000002、20000003这两个班级的学生:

Java代码 复制代码 收藏代码
  1. String[] ids = new String[2];   
  2. ids[0] = "20000002";   
  3. ids[1] = "20000003";   
  4. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(ids);   
  5. for( StudentEntity entityTemp : studentList){   
  6.     System.out.println(entityTemp.toString());   
  7. }


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/399805.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

git 脚本

echo $PWD message$1 content. if [ ! -n "$1" ] ;thenmessagedatemessage$message 推送到服务器echo $message elseecho "$1" figit add . git commit -m "$message " git push 转载于:https://www.cnblogs.com/whm-blog/p/7527271.html

composer安装特别慢的解决方案

https://www.cnblogs.com/djwhome/p/9322287.html composer安装特别慢的解决方案 在项目开发的时候 有许多新的依赖要按照 就需要用到composer 但是由于国内安装下载速度贼慢(国外的网站连接速度太慢&#xff0c;并且随时可能被墙) 安装一个excel扩展(composer require maatw…

好的积分不等式

转自 http://pxchg1200.is-programmer.com/?page7 转载于:https://www.cnblogs.com/zhangwenbiao/p/4738960.html

Jsoup(三)-- Jsoup使用选择器语法查找DOM元素

1.Jsoup可以使用类似于CSS或jQuery的语法来查找和操作元素. 2.实例如下&#xff1a; public static void main(String[] args) throws Exception{// 创建httpClient实例CloseableHttpClient httpClient HttpClients.createDefault();// 创建httpGet实例HttpGet httpGet new H…

Ubuntu 中改变文件的默认打开方式(转)

源自&#xff1a;Ubuntu 中改变文件的默认打开方式 1. 相关配置文件 [plain] view plaincopyprint? 全局配置 /etc/gnome/defaults.list /usr/share/applications/mimeinfo.cache 个人配置 ~/.local/share/applications/mimeapps.list ~/.local/share/applications/mimei…

使用PhpSpreadsheet将Excel导入到MySQL数据库

使用PhpSpreadsheet将Excel导入到MySQL数据库 日常开发中&#xff0c;我们经常遇到这样的场景&#xff0c;需要将一个Excel表格数据如客户信息、学生成绩表导入到系统数据库中&#xff0c;然后在系统中进行进一步操作&#xff0c;如给导入的客户群发短信&#xff0c;统计学生成…

spring-test的简单实用方式

为什么80%的码农都做不了架构师&#xff1f;>>> 1. 通过maven引入spring-test框架 <dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.2.0.RELEASE</version> </…

Maven学习-目录结构

1. 什么是Maven 2. 如何用Maven来构建项目 3. Maven项目的目录结构 Maven约定了一套规则来创建和构建项目。得益于Maven的一些约定&#xff0c;我们只要学习相对很少的命令就可以创建和管理我们的项目。在项目的目录结构上&#xff0c;Maven有一套约定的通用的目录结构。 使用一…

用JQuery中的Ajax方法获取web service等后台程序中的方法

用JQuery中的Ajax方法获取web service等后台程序中的方法 1、准备需要被前台html页面调用的web Service&#xff0c;这里我们就用ws来代替了&#xff0c;代码如下&#xff1a; using System;using System.Collections.Generic;using System.Data;using System.Linq;using Syste…

WordPress路径相关函数总结

WordPress路径相关函数总结 wordpress各种获取路径和URl地址的函数总结 wp_upload_dir() 返回WordPress上传目录的地址&#xff0c;是一个数组&#xff0c;包含一系列与上传地址相关的信息。 <?php $upload_dir wp_upload_dir(); ?>

WordPress后台添加侧边栏菜单

https://my.oschina.net/shunshun/blog/78193 https://www.ludou.org/add-admin-menu-in-wordpress.html 添加WordPress顶级管理菜单其实也是一件非常简单的事情&#xff0c;使用两个WordPress内置函数就可以解决问题&#xff0c;分别是add_menu_page()和 add_action()&#xf…

如何看待和选择基础设施软件

1&#xff0c; 广泛性 2&#xff0c; 通用性 3&#xff0c; 稳定性 4&#xff0c; 功能 5&#xff0c; 遇到问题能否快速查到资料 6&#xff0c; 文档是否齐全 不一定是最先进的技术就是最好的。 采用什么样的技术栈&#xff1a; 一定要主流&#xff0c; 很少做到技术专家的地步…

Android 常见错误

2019独角兽企业重金招聘Python工程师标准>>> 1. org.apache.http.conn.HttpHostConnectException: Connection to refused 权限问题: <uses-permission android:name"android.permission.INTERNET"/> 2. 浏览器直接输入url可以get&#xff0c;http …

使用BootStrap框架设置全局CSS样式

一、排版 标题 HTML 中的所有标题标签&#xff0c;<h1> 到 <h6> 均可使用。另外&#xff0c;还提供了 .h1 到 .h6 类&#xff0c;为的是给内联&#xff08;inline&#xff09;属性的文本赋予标题的样式。 <h1>这是一个h1标签</h1><h2>这是一个h2…

SVN初步学习教程

本文目的 让未使用过版本控制器软件或者未使用过subversion软件的人员尽快上手。 subversion的使用技巧很多&#xff0c;这里只总结了最小使用集&#xff0c;即主要的基本功能&#xff0c;能够用来应付日常工作。 因此不涉及subversion服务器端的搭建和配置。 为什么要使用版本…

wordpress 添加自定义的一定级菜单

//添加项级菜单 function register_bwp_menu_page(){ add_menu_page( title标题, 菜单标题, administrator, ../wp-content/themes/yourthemes/myplugin/myplugin-index.php,,,100); } add_action(admin_menu, register_bwp_menu_page); myplugin目录为 yourthemes 主题目…

V2EX大牛的指点

2019独角兽企业重金招聘Python工程师标准>>> first&#xff1a; 我认识一些深圳、杭州、北京的朋友&#xff0c;他们往往更关注以下内容&#xff1a; 1. 代码&#xff08;包括注释&#xff09;的规范性、可维护性 2. 参与一些算法的研究与实现、开源库的创建与维护…

python-实现动态web服务器

# encodingutf-8 import socket from multiprocessing import Process import re import sys# 设置静态文件根目录 HTML_ROOT_DIR ./htmlWSGI_PYTHON_DIR ./wsgipythonclass HTTPServer(object):def __init__(self, application):self.server_socket socket.socket(socket.A…

Android中shape的使用

本人在美工方面一直是比较白痴的&#xff0c;对于一些颜色什么乱七八糟的非常头痛&#xff0c;但是在Android编程中这又是经常涉及到的东西&#xff0c;没办法&#xff0c;只有硬着头皮上。 Android中常常使用shape来定义控件的一些显示属性&#xff0c;今天看了一些shape的使用…

PHP遍历数组的几种方法

这三种方法中效率最高的是使用foreach语句遍历数组。从PHP4开始就引入了foreach结构&#xff0c;是PHP中专门为遍历数组而设计的语句&#xff0c;推荐大家使用。先分别介绍这几种方法 PHP中遍历数组有三种常用的方法&#xff1a; 一、使用for语句循环遍历数组&#xff1b; 二、…