笔记53 Mybatis快速入门(四)
动态SQL
1.if
假设需要对Product执行两条sql语句,一个是查询所有,一个是根据名称模糊查询。那么按照现在的方式,必须提供两条sql语句:listProduct和listProductByName然后在调用的时候,分别调用它们来执行。如下所示:
Product.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="mybatis.pojo"> <select id="listProduct1" resultType="Product">
select * from product
</select>
<select id="listProductByName" resultType="Product">
select *
from product where name like concat('%',#{name},'%')
</select>
</mapper>
Test.java
package mybatis.test; import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import mybatis.pojo.Product; public class testIf {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession(); System.out.println("查询所有的");
List<Product> products = session.selectList("listProduct1");
for (Product product : products) {
System.out.println(product);
} System.out.println("模糊查询");
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", "a");
List<Product> products2 = session.selectList("listProductByName",
params);
for (Product product : products2) {
System.out.println(product);
} session.commit();
session.close();
}
}
如果Product的字段比较多的话,为了应付各个字段的查询,那么就需要写多条sql语句,这样就变得难以维护。这个时候,就可以使用Mybatis 动态SQL里的if标签
<select id="listProduct2" resultType="Product">
select * from product
<if test="name!=null">
where name like concat('%',#{name},'%')
</if>
</select>
如果没有传参数name,那么就查询所有,如果有name参数,那么就进行模糊查询。这样只需要定义一条sql语句即可应付多种情况了,在测试的时候,也只需要调用这么一条sql语句listProduct 即可。
System.out.println("查询所有的");
List<Product> products = session.selectList("listProduct2");
for (Product product : products) {
System.out.println(product);
} System.out.println("模糊查询");
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", "a");
List<Product> products2 = session.selectList("listProduct2", params);
for (Product product : products2) {
System.out.println(product);
}
2.where
<1>如果要进行多条件判断,如下所示:
<select id="listProduct2" resultType="Product">
select * from product
<if test="name!=null">
where name like concat('%',#{name},'%')
</if>
<if test="price!=0">
and price>=#{price}
</if>
</select>
System.out.println("多条件查询");
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", "a");
params.put("price", "10");
List<Product> products2 = session.selectList("listProduct4", params);
for (Product product : products2) {
System.out.println(product);
}
这么写的问题是:当没有name参数,却有price参数的时候,执行的sql语句就会是:select * from product_ and price > 10。这样就会报错。
这个问题可以通过<where>标签来解决,如代码所示:
<select id="listProduct4" resultType="Product">
select * from product
<where>
<if test="name!=null">
and name like concat('%',#{name},'%')
</if>
<if test="price!=null and price!=0">
and price>#{price}
</if>
</where>
</select>
<where>标签会进行自动判断:
如果任何条件都不成立,那么就在sql语句里就不会出现where关键字
如果有任何条件成立,会自动去掉多出来的 and 或者 or。
所以map里面两个参数无论是否提供值都可以正常执行。
<2>与where标签类似的,在update语句里也会碰到多个字段相关的问题。 在这种情况下,就可以使用set标签:
<update id="updateProduct" parameterType="Product">
update product
<set>
<if test="name!=null">name=#{name},</if>
<if test="price!=null">price=#{price}</if>
</set>
where id=#{id}
</update>
Product product = new Product();
product.setId(6);
product.setName("product xzz");
product.setPrice(6.99f);
session.update("updateProduct", product);
<3>trim 用来定制想要的功能,比如where标签就可以用以下代码替换:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
set标签可以用以下代码来替换:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
示例:
<select id="listProduct5" resultType="Product">
select * from product
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="name!=null">
and name like concat('%',#{name},'%')
</if>
<if test="price!=null and price!=0">
and price>#{price}
</if>
</trim>
</select>
<update id="updateProduct2" parameterType="Product">
update product
<trim prefix="SET" suffixOverrides=",">
<if test="name!=null">name=#{name},</if>
<if test="price!=null">price=#{price}</if>
</trim>
where id=#{id}
</update>
3.choose
Mybatis里面没有else标签,但是可以使用when otherwise标签来达到这样的效果。
<select id="listProduct6" resultType="Product">
select * from product
<where>
<choose>
<when test="name!=null">
and name like concat('%',#{name},'%')
</when>
<when test="price!=null and price!=0">
and price>#{price}
</when>
<otherwise>
and id>1
</otherwise>
</choose>
</where>
</select>
作用: 提供了任何条件,就进行条件查询,否则就使用id>1这个条件。
System.out.println("多条件查询");
Map<String, Object> params = new HashMap<String, Object>();
// params.put("name", "a");
// params.put("price", "10");
List<Product> products2 = session.selectList("listProduct6", params);
for (Product products : products2) {
System.out.println(products);
}
查询结果:
如果去掉注释,提供查询条件,则结果如下:
4.foreach
适用情况如下所示:
<select id="listProduct7" resultType="Product">
select * from product
where id in
<foreach item="item" index="index" collection="list" open="("
separator="," close=")">
#{item}
</foreach>
</select>
collection :collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合
item : 表示在迭代过程中每一个元素的别名
index :表示在迭代过程中每次迭代到的位置(下标)
open :前缀
close :后缀
separator :分隔符,表示迭代时每个元素之间以什么分隔
测试:
List<Integer> idsIntegers = new ArrayList<Integer>();
idsIntegers.add(1);
idsIntegers.add(3);
idsIntegers.add(5); List<Product> products = session.selectList("listProduct7", idsIntegers); for (Product product : products) {
System.out.println(product);
}
结果:
5.bind
bind标签就像是再做一次字符串拼接,方便后续使用。如下所示,在模糊查询的基础上,把模糊查询改为bind标签。
<select id="listProductByName" resultType="Product">
select *
from product
where name like concat('%',#{name},'%')
</select>
<select id="listProductByName2" resultType="Product">
<bind name="likename" value="'%'+name+'%'"/>
select *
from product
where name like #{likename}
</select>
笔记53 Mybatis快速入门(四)的更多相关文章
- MyBatis学习笔记(一)——MyBatis快速入门
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4261895.html 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优 ...
- 笔记56 Mybatis快速入门(七)
相关概念介绍(二) 6.一级缓存 <1>在一个session里查询相同id的数据 package mybatis.annotation; import java.io.IOExceptio ...
- 笔记50 Mybatis快速入门(一)
一.Mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...
- mybatis快速入门(四)
mybatis动态标签<where><if><foreach>以及sql片段 1.创建一个包装类UserQueryVo.java package cn.my.myb ...
- 笔记55 Mybatis快速入门(六)
相关概念介绍(一) 1.日志 有时候需要打印日志,知道mybatis执行了什么样的SQL语句,以便进行调试.这时,就需要开启日志,而mybatis自身是没有带日志的,使用的都是第三方日志,这里介绍如何 ...
- 笔记54 Mybatis快速入门(五)
Mybatis中注解的使用 1.XML方式的CRUD 新增加接口CategoryMapper ,并在接口中声明的方法上,加上注解对比配置文件Category.xml,其实就是把SQL语句从XML挪到了 ...
- 笔记52 Mybatis快速入门(三)
一.更多查询 1.模糊查询 修改Category.xml,提供listCategoryByName查询语句select * from category where name like concat(' ...
- 笔记51 Mybatis快速入门(二)
Mybatis的CRUD 1.修改配置文件Category.xml,提供CRUD对应的sql语句. <?xml version="1.0" encoding="UT ...
- MyBatis学习总结(一)——MyBatis快速入门
一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...
随机推荐
- LeetCode Array Easy 189. Rotate Array
---恢复内容开始--- Description Given an array, rotate the array to the right by k steps, where k is non-ne ...
- ASP.NET MVC 学习笔记之View 和Redriect的区别
首先先说一下Redriect 和RedirectToAction 两个没什么区别,都是向浏览器发送302 Found相应,再有浏览器向对应的url进行请求 只是参数的意义不同而已 再说Redirect ...
- 使用source insert 查看Linux内核源码
先配置下source insert软件,添加工程文件时可以支持各种类型的文件 “ Options ” --> “ Preferences ” ---> “ Languages ” ---& ...
- 统计所有小于非负整数 n 的质数的数量,埃拉托斯特尼筛法
素数的定义:质数又称素数.一个大于1的自然数,除了1和它自身外,不能被其他自然数整除的数叫做质数. 1.暴力算法: 令i=2; 当i<n的时候,我们循环找出2-i的质数,即让i%(2~i-1), ...
- CSS3 object-position/object-fit
object-position和object-fit只针对替换元素有作用,也就是form表单家族控件系列,老牌劲旅img图片,HTML5新贵video视频等元素(一般有src属性的). 一.objec ...
- redis-config.properties属性资源文件
redis.host=192.168.200.128redis.port=6379redis.pass=redis.database=0redis.maxIdle=300redis.maxWait=3 ...
- java中设置http响应头控制浏览器禁止缓存当前文档内容
response.setDateHeader("expries", -1); response.setHeader("Cache-Control", " ...
- AcWing 197. 阶乘分解 (筛法)打卡
给定整数 N ,试把阶乘 N! 分解质因数,按照算术基本定理的形式输出分解结果中的 pipi 和 cici 即可. 输入格式 一个整数N. 输出格式 N! 分解质因数后的结果,共若干行,每行一对pi, ...
- PHP中关于Phar的学习
什么是phar 一个PHP程序往往是由多个文件组成的,如果能够集中为一个文件来分发和运行是很方便的.phar便应运而生.大概跟java的jar文件是差不多类似的.但是php的phar文件是可以由php ...
- 数据结构学习笔记——顺序数组2
接着昨天的数组操作,数组初始化好了,我们要往里面添加元素,可以在尾部追加或者插入,刚开始数组为空,所以先追加 int AppendList(SqList* pArr, ElemType val) { ...