一、基于MyBatis动态SQL语句

1、if标签

实体类Product的字段比较多的时候,为了应付各个字段的查询,那么就需要写多条SQL语句,这样就变得难以维护。

此时,就可以使用MyBatis动态SQL里的if标签

<select id="listProduct" resultType="Product">
select * from product_table
<if test="name!=null">
where name like concat('%',#{name},'%')
</if>
</select>

这种写法,如果没有传递参数name,那么就查询所有,如果有name就进行模糊查询。

这样就定义了一条SQL语句,应付了多种情况。

TestMyBatis测试如下:

package com.demo;
import java.io.IOException;
import java.io.InputSteam;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.io.Resouces;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.demo.pojo.Product; public class TestMyBatis{
public static void main(String[] args) throws IOException{
String resouce="mybatis-config.xml";
InputSteam inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=sqlSessionFactory.openSession(); System.out.println("查询所有的数据");
List<Product> list1=session.selectList("listProduct");
for(Product p:list1){
System.out.println(p);
} System.out.println("模糊查询");
Map<String,Object> params=new HashMap<>();
params.put("name","a");
List<Product> list2=session.selectList("listProduct",params);
for(Product p:list2){
System.out.println(p);
} session.commit();
session.close(); }
}

2、where标签

where标签与if标签对应,如果要进行多个条件判断,就会写成这样

<select id="listProduct" resultType="Product">
select * from product_table
<if test="name!=null">
where name like concat('%',#{name},'%')
</if>
<if test="price!=0">
and price>#{price}
</if>
</select>

这种写法,会出现问题,当没有name参数,却有price参数的时候,执行的sql语句是:

select * from product_table and price>10

执行会报错的。

解决这种问题时,就要使用where标签

<select id="listProduct" resultType="Product">
select * from product_table
<where>
<if test="name!=null">
where name like concat('%',#{name},'%')
</if>
<if test="price!=0">
and price>#{price}
</if>
<where>
</select>

<where>标签会进行自动判断,如果任何条件都不成立,那么sql语句中就不会出现where关键字,如果有任何条件成立,会自动去掉多出来的and,or

3、set标签

与where标签类似,在update语句中碰到多个字段的问题。这种情况下,就会使用set标签

<update id="updateProduct" parameterType="Product">
update product_table
<set>
<if test="name!=null">name=#{name},</if>
<if test="price!=null">price=#{price}</if>
</set>
where id=#{id}
</update>

4、trim标签

用来制定想要的功能,

trim标签替换where标签如下:

<trim prefix="WHERE" prefixOverrides="AND|OR"></trim>

trim标签替换set标签如下:

<trim prefix="SET" suffixOverrides=","></trim>

使用原生的标签配置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="com.demo.pojo">
<select id="listProduct" resultType="Product">
select * from product_table
<where>
<if test="name!=null">
and name like concat('%',#{name},'%')
</if>
<if test="price!=null and price!=0">
and price > #{price}
</if>
</where>
</select> <update id="updateProduct" parameterType="Product" >
update product_table
<set>
<if test="name != null">name=#{name},</if>
<if test="price != null">price=#{price}</if>
</set>
where id=#{id}
</update>
</mapper>

使用trim标签配置的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="com.demo.pojo">
<select id="listProduct" resultType="Product">
select * from product_table
<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="updateProduct" 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>
</mapper>

5、choose标签

if-else时候的情况,因为MyBatis中没有else标签,可以使用when otherwise标签,但是要在choose标签包裹里

<select id="listProduct" resultType="Product">
select * from product_table
<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>#{id}
</otherwise>
</choose>
</where>
</select>

6、foreach标签

用于sql中使用in的语法

例如sql:

--名字要么是apple要么是banana
select * from product_table where name in("apple,banana")
--薪水要么等于3000要么等于6000
select * from employees where salary in(3000,6000)

foreach标签使用

<select id="listProduct" resultType="Product">
select * from product_table
where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">#{item}</foreach>
</select>

7、bind标签

相当于做一次字符串拼接,方便后续使用

    <select id="listProduct" resultType="Product">
<bind name="likename" value="'%'+name+'%'" />
select * from product_table where name like #{likename}
</select>

本来的模糊查询是这样:

<select id="listProduct" resultType="Product">
select * from product_table where name like concat('%',#{0},'%')
</select>

十、 持久层框架(MyBatis)的更多相关文章

  1. 从零搭建springboot服务02-内嵌持久层框架Mybatis

    愿历尽千帆,归来仍是少年 内嵌持久层框架Mybatis 1.所需依赖 <!-- Mysql驱动包 --> <dependency> <groupId>mysql&l ...

  2. java持久层框架mybatis如何防止sql注入

    看到一篇很好的文章:http://www.jfox.info/ava-persistence-framework-mybatis-how-to-prevent-sql-injection sql注入大 ...

  3. Java数据持久层框架 MyBatis之背景知识三

    摘录自:http://www.cnblogs.com/lcngu/p/5437281.html 对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.or ...

  4. Java数据持久层框架 MyBatis之API学习一(简介)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  5. Java数据持久层框架 MyBatis之背景知识二

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  6. Java数据持久层框架 MyBatis之背景知识一

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  7. 开源顶级持久层框架——mybatis(ibatis)——day02

    mybatis第二天    高级映射 查询缓存 和spring整合          课程复习:         mybatis是什么?         mybatis是一个持久层框架,mybatis ...

  8. Java持久层框架Mybatis入门

    MyBatis是什么 MyBatis是Java的持久层框架,GitHub的star数高达15.8k,是Java技术栈中最热门的ORM框架之一.它支持自定义SQL.存储过程以及高级映射,可以通过XML或 ...

  9. 开源顶级持久层框架——mybatis(ibatis)——day01

    mybatis-day01     1.对原生态jdbc程序中的问题总结         1.1环境             java环境:jdk             eclipse:indigo ...

  10. 整合使用持久层框架mybatis 使用SqlSessionTemplate模板类与使用映射接口 对比

    spring中整合使用mybatis的用法总结 一:在Spring配置Mybatis 第一步:将mybatis-spring类包添加 到项目的类库中 第二步:编写spring和持久层衔接的xml文件, ...

随机推荐

  1. JavaScript基本内容

    注释: /*多行 注释*/ //单行注释 变量: //变量均为对象,常用类型:String.Number.Boolean.Array.Object var value = "hello&qu ...

  2. nodejs的dependency.md

    dependency和devDependency的区别 package-a --- package-b (dependency) --- | --- package-c (devDependency) ...

  3. 如何用conda安装软件|处理conda安装工具的动态库问题

    conda的确是一个非常好的工具,对于初学者而言,安装软件就跟用XXX软件管理器一样方便.正因为他如此便利,以至于我介绍如何手动安装工具时,总有人问我为啥不用conda. 我用conda,并且用的很好 ...

  4. sql存储过程基本语法

    一.定义变量 --简单赋值 declare @a int print @a --使用select语句赋值 declare @user1 nvarchar() select @user1='张三' pr ...

  5. [转]pugixml使用教程

    转自:https://www.cnblogs.com/ltm5180/p/3989125.html pugixml介绍 pugixml是一个高性能.轻量级并且简单易用的xml解析库,支持UTF8 en ...

  6. Math.abs(~2020) 按位取反后的绝对值是多少 2021, 按位取反后,比正数多1

    Math.abs(~2020)  按位取反后的绝对值是多少 2021, 按位取反后,比正数多1 int 值的取值 范围:   -128 ---  127   之间, 0000 0000     按位取 ...

  7. STL——map

    看到map这里,都不知道它主要是干嘛的,你有没有这样的疑问. map的主要作用:提供对T类型的数据进行快速和高效的检索 .C++ STL中标准关联容器set, multiset, map, multi ...

  8. Java 层序创建和遍历二叉树

    直接上代码 package te.com; import java.util.LinkedList; import java.util.Queue; import java.util.logging. ...

  9. DEBUG(2)--函数的输入参数要做适当的检查

      今天在调试程序时发现,在单步运行的情况下,程序执行没有问题,但是直接运行就会出问题.出问题的代码如下 for(int col=0;col<=9;++col) { int killid=Pos ...

  10. Java访问Redis

    Redis的数据类型总共有如下几种 1.String(字符串) 2.List(列表),字符串列表,有序 3.Hash(哈希),可以存储类似于数据库的表结构 4.Set(集合),无序,不可重复 5.ZS ...