JavaWeb学习笔记(动态SQL)
JavaWeb学习笔记(动态SQL)
- 动态SQL中的元素
- < if>元素
- < choose>、< when>、< otherwise>元素
- < where>、< tirm>元素
- < set>元素
- < foreach>元素
- < bind>元素
动态SQL中的元素
动态SQL消除了之前版本需要了解的大多数元素,使用不道原来一半的元素就能完成所需的工作。
MyBatis动态SQL中的主要元素
元素 | 说明 |
---|---|
< if> | 判断语句,用于单条件分支判断 |
< choose>(< when>、< otherwise>) | 相当于Java中的switch…case…default语句,用于多条件分支判断 |
< where>、< tirm>、< set> | 辅助元素,用于处理一些SQL拼装、特殊字符问题 |
< foreach> | 循环语句,常用于int语句等列举条件中。 |
< bind> | 从OGNL表达式中创建一个变量,并将其绑定到上下文,常用于模糊查询的sql中 |
< if>元素
< if>是MyBatis中最常用的元素,类似于Java中的if语句,主要用于实现某些简单的条件选择。
示例
(1)创建一个名为dongtaisql的Web项目,将之前mybatis项目中的src导入到其中
(2)创建一个com.itheima.utils包,创建一个MyBatisUtils工具类。
package com.itheima.utils;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory=null;static{try{Reader reader=Resources.getResourceAsReader("mybatis-config.xml");sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);}catch(Exception e){e.printStackTrace();}}public static SqlSession getSession(){return sqlSessionFactory.openSession();}
}
(3)修改映射文件CustomerMapper.xml在映射文件中使用< if>元素编写根据客户姓名和职业组合条件查询客户信息列表的SQL
<select id="findCustomerByNameAndJobs"parameterType="com.itheima.po.Customer" resultType="com.itheima.po.Customer">select *from t_customer where 1=1<if test="username!=null and username !=''">and username like concat('%',#{username},'%')</if><if test="jobs!=null and jobs !=''">and jobs=#{jobs}</if></select>
(4)在测试类MyBatisTest中,编写测试方法。
@Testpublic void findCustomerByNameAndJobsTest(){SqlSession session=MybatisUtils.getSession();Customer customer=new Customer();customer.setuserName("jack");customer.setJobs("teacher");List <Customer> customers=session.selectList("com.itheima.mapper"+".CustomerMapper.findCustomerByNameAndJobs",customer);for(Customer customer2:customers){System.out.println(customer2);}session.close();}
如果将封装到Customer对象中的javk和两行代码注释掉
< choose>、< when>、< otherwise>元素
在使用< if>元素时,只要test属性中的表达式为true,就会执行元素中的条件语句,但在实际中有时字需要从多个选项中选择一个去执行。
示例:
“当客户名称不为空,只根据客户名称进行客户筛选;当客户名称为空,而客户职业不为空,则只要根据用户职业进行客户筛选,当客户名称和客户职业都为空,则要求查询出所有电话不为空的客户信息。”
(1)在映射文件CustomerMapper.ml中使用< choose>、< when>、< otherwise>元素执行上述情况的动态SQL代码
<select id="findCustomerByNameOrJobs" parameterType="com.itheima.po.Customer" resultType="com.itheima.po.Customer">select *from t_customer where 1=1<choose><when test="username !=null and username!=''">and username like concat('%',#{username},'%')</when><when test="jobs !=null and jobs!=''">and jobs =#{jobs}</when><otherwise>and phone is not null</otherwise></choose></select>
(2)在测试类中添加测试方法
@Testpublic void findCustomerByNameOrJobsTest(){SqlSession session=MybatisUtils.getSession();Customer customer=new Customer();customer.setuserName("jack");customer.setJobs("teacher");List <Customer> customers=session.selectList("com.itheima.mapper"+".CustomerMapper.findCustomerByNameOrJobs",customer);for(Customer customer2:customers){System.out.println(customer2);}session.close();}
(3)注释掉customer.setuserName(“jack”);
(4)注释掉customer.setJobs(“teacher”);
< where>、< tirm>元素
上述两个示例都用到了where 1=1,我们可以将其的1=1去掉,MyBatis提供了< where>元素。< where>会自动判断组合条件下拼装的SQL语句,只有< where>元素内条件成立是,才会拼接SQL中加入where关键字,否则将不会添加,即使where后面有多余的"AND"或"OR",< where>元素也会自动将他们去除。
上上<select id=“findCustomerByNameAndJobs”
<select id="findCustomerByNameAndJobs"parameterType="com.itheima.po.Customer" resultType="com.itheima.po.Customer">select *from t_customer <where><if test="username!=null and username !=''">and username like concat('%',#{username},'%')</if><if test="jobs!=null and jobs !=''">and jobs=#{jobs}</if><where></select>
除了使用< where>元素,我们还可以使用< tirm>元素来定制需要的功能,上述代码可以修改为:
<select id="findCustomerByNameAndJobs"parameterType="com.itheima.po.Customer" resultType="com.itheima.po.Customer">select *from t_customer <tirm prefix="where" prefixOverrides="and"><if test="username!=null and username !=''">and username like concat('%',#{username},'%')</if><if test="jobs!=null and jobs !=''">and jobs=#{jobs}</if></tirm></select>
< tirm>的作用是去除一些特殊字符串,其中prefix表示语句的前缀,而prefixOverride属性代表的是需要去除的那些特殊字符串。
< set>元素
如果想要更新一个对象,就需要发送所有的字段给持久化对象,实际应用中只是更新某一个字段或几个字段,执行效率非常的差,< set>方法可以让程序只更新需要更新的字段。
示例:
(1)修改CustomerMapper.xml,
<update id="updateCustomer" parameterType="com.itheima.po.Customer">update t_customer <set><if test="username !=null and username !=''">username=#{username},</if><if test="jobs !=null and jobs !=''">jobs=#{jobs},</if><if test="phone !=null and phone !=''">phone =#{phone},</if></set>where id=#{id}</update>
(2)在测试类中编写测试方法
@Testpublic void updateCustmoerTest() throws IOException{String resource="mybatis-config.xml";InputStream inputStream=Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession=sqlSessionFactory.openSession();Customer customer=new Customer();customer.setId(3);customer.setPhone("13311111234");int rows=sqlSession.update("com.itheima.mapper"+".CustomerMapper.updateCustomer",customer);if(rows>0){System.out.println("你成功修改了"+rows+"条数据");}else{System.out.println("执行修改操作失败");}sqlSession.commit();sqlSession.close();}
< foreach>元素
< foreach>元素提供了一种用于数组和集合循环遍历的方式。
< foreach>元素通常在构建IN条件语句时使用,使用方式如下:
<select id="findCustomerByIds" parameterType="List" resultType="com.itheima.po.Customer">select *from t_customer where id in<foreach item="id" index="index" collection="list"open="(" separator="," close=")">#{id}</foreach></select>
< foreach>有几种属性
1.item:配置循环中当前的元素
2.index:配置的是当前元素在集合位置的下标
3.collection:配置list是传递过来的参数类型,可以是一个array、list等
4.open和close:配置的是以什么符号将这些集合元素包装起来
5.separator:配置各个元素的间隔符
在测试类中添加测试方法
@Testpublic void findCustomerByIdTest(){SqlSession session=MybatisUtils.getSession();List<Integer> ids=new ArrayList<Integer>();ids.add(1);ids.add(2);List <Customer> customers=session.selectList("com.itheima.mapper"+".CustomerMapper.findCustomerByIds",ids);for(Customer customer:customers){System.out.println(customer);}session.close();}
< bind>元素
< bind>元素常用来进行模糊查询,MyBatis的< bind>元素可以通过OGNL表达式来创建一个上下文变量,使用方法如下:
</select><select id="findCustomerByNames" parameterType="com.itheima.po.Customer" resultType="com.itheima.po.Customer"><bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'"/>select *from t_customerwhere username like #{pattern_username}</select>
其中有几个属性< value>属性就是拼接的查询字符串,其中_parameter.getUsername()表示传递进来的参数。
编写测类
@Testpublic void findCustomerByNameTest(){SqlSession session=MybatisUtils.getSession();Customer customer=new Customer();customer.setuserName("j");List <Customer> customers=session.selectList("com.itheima.mapper"+".CustomerMapper.findCustomerByNames",customer);for(Customer customer2:customers){System.out.println(customer2);}session.close();}
JavaWeb学习笔记(动态SQL)相关推荐
- JavaWeb学习笔记(数据库、SQL语句、数据查询语法、完整性约束、编码、备份和恢复数据、多表查询)
数据库.SQL语句.数据查询语法.完整性约束.编码.备份和恢复数据.多表查询 JavaWeb学习笔记 数据库 数据库概念 基本命令 启动和关闭mysql服务器 客户端登录退出mysql SQL语句 S ...
- B站狂神说JavaWeb学习笔记
JavaWeb学习笔记(根据b站狂神说java编写) 1.基本概念 1.1 前言 静态Web: 提供给所有人看数据不会发生变化! HTML,CSS 动态Web: 有数据交互,登录账号密码,网站访问人数 ...
- Javaweb学习笔记(JSP标准标签库)
Javaweb学习笔记(JSP标准标签库) JSTL入门 安装和测试JSTL JSTL中的Core标签库 < c:out>标签 标签 标签 < c:catch>标签 标签 标签 ...
- JavaWeb学习笔记(5)-B站尚硅谷
文章目录 十四.书城项目第三阶段--优化 (1)页面jsp动态化 (2)抽取页面中相同的内容 A.登录成功的菜单 B.base.css.jQuery标签 C.每个页面的页脚 D.manager模块的菜 ...
- javaweb学习笔记2(jquery的使用,以及常用的方法,选择器,过滤器)
javaweb学习笔记2 javascript正则表达式 regfxp对象 方式1: var putt=new RegExp("e");//表示要求字符串中必须包含字符串evar ...
- 【javaweb学习笔记】servlet-api,filter和Listener
javaweb学习笔记 1. servlet-api 1.1 servlet初始化 1.2 ServletContext和context-param 2. 什么是业务层 3. IOC 3.1 耦合/依 ...
- 【Javaweb学习笔记】在Eclipse中创建Web项目
[Javaweb学习笔记]在Eclipse中创建Web项目 哈喽大家好,这里是Java框架学习笔记专栏第二期 本期内容--在Eclipse中创建Web项目 前期回顾: 第一期--schema约束 笔者 ...
- javaWeb学习笔记1—前端三件套 HTML CSS JavaScript
学习视频地址 javaWeb学习笔记-前端三件套 HTML CSS JavaScript 1.字体标签 2. 字符实体 3.标题标签 4.超链接 5.列表标签 6. img标签 路径 7.表格 8.i ...
- JavaWeb学习笔记(软件系统体系结构、Tomcat、Web应用、HTTP协议)
JavaWeb学习笔记 JavaWeb学习笔记 软件系统体系结构 常见软件系统体系结构C/S.B/S Web资源 Web服务器 Tomcat Tomcat概述 安装.启动.配置Tomcat Web应用 ...
最新文章
- 生产者与消费者-1:N-基于list
- unity角色移动代码_教你3个步骤实现Unity小地图
- 定义python的色条_Python:定义颜色曲线部分
- 因为高考砸了,所以大学一直在超越
- eclipse中js文件报missing semicolon
- 【LCT】遥远的国度(P3979)
- 2014522920145316《信息安全系统设计基础》实验一 开发环境的熟悉
- 如何在 GitHub 上大显身手?
- 最近遇到个关于接口的奇怪的问题
- mysql 程序无法连接_程序无法连接到服务器不知道怎么解决
- 一天破万:二十一个微信公众号推广技巧
- C语言 猜数游戏 首先由计算机产生一个随机数,并给出这个随机数所在的区间,然后有游戏者猜测这个数。猜中游戏结束,并可以重新挑战,猜错重新给出提示,如果猜测超过八次游戏失败。
- 大湾区国际创客峰会暨MFSZ2021重磅回归!
- 译(自编码器) Hinton2006---Reducing the Dimensionality of Data with Neural Networks
- 利用迪纳波利 (DINAPOLI) 等级进行交易
- 【华人学者风采】杨鸣波 四川大学
- 学习jqr2013-05-11
- NOIP 2016 PJ T4 魔法阵
- dig命令的使用方法
- 用centOS 7安装cadence搭建适合IC Design的科研环境
热门文章
- win10部分软件中文显示为“口口口”
- 为 KubeSphere 集群启用免费的泛域名 SSL 证书并实现证书自动更新和分发
- ECDSA host key for IP has changed and you have requested strict checking.Host key verification fail
- CTFHub Linux 动态加载
- 智能指针循环引用问题
- Ubuntu Android Studio 无法输入中文
- Android自定义View 自定义组合控件
- scrapy 爬取新浪微博 的微博列表及微博内容
- 计算机专业考研选择研究
- MIUI13 USB调试Android应用失败INSTALL_FAILED_USER_RESTRICTED