一、基于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. Entity Framework Core一键生成实体命令

    打开Vs中工具——Nug包管理器——程序包管理控制台 设置启动项目为存储实体模型的类库或控制台 Scaffold-DbContext  "数据库连接字符串" Microsoft.E ...

  2. 前端分页插件bootstrapPaginator的使用

     引入bootstrap-paginator.js <table class="table table-striped table-bordered table-hover dataT ...

  3. 基于 Python 和 Pandas 的数据分析(1)

    基于 Python 和 Pandas 的数据分析(1) Pandas 是 Python 的一个模块(module), 我们将用 Python 完成接下来的数据分析的学习. Pandas 模块是一个高性 ...

  4. 小tip: margin:auto实现绝对定位元素的水平垂直居中

    转载自:http://www.zhangxinxu.com/wordpress/?p=3794 一.绝对定位元素的居中实现 如果要问如何CSS实现绝对定位元素的居中效果,很多人心里已经有答案了. 兼容 ...

  5. Python中cPickle

    cPickle模块: 在python中,一般可以使用pickle类来进行python对象序列化,而cPickle提供了一个更快速简单的接口,如python文档所说:“cPickle - A faste ...

  6. 力扣 报错 runtime error: load of null pointer of type 'const int'

    runtime error: load of null pointer of type 'const int' 要求返回的是int* 解决方案 1.指针使用malloc分配空间 用 int * p = ...

  7. npm install 报错ERR! 404 Not Found: event-stream@3.3.6

    在win下开发的node工程,在linux下用dockerfile部署时,遇到npm install时报错 Step / : RUN npm install ---> Running in 2e ...

  8. cocos2dx spine之一 :spine缓存 (c++ & lua)

    cocos2dx版本为3.10 1.在使用spine的过程中,发现了一个比较严重的问题:每次创建SkeletonAnimation的时候都会很卡,即使是使用同一个骨骼数据skeletonData. 跟 ...

  9. [Spring] 关联类和bean | autowire=byName|byType

    ref:https://www.tutorialspoint.com/spring/spring_autowiring_byname.htm project:Working Set: Spring&g ...

  10. eclipse---->error and exception 和常用配置

    1.eclipse打开后报错:An internal error occurred during: "Initializing Java Tooling". java.lang.N ...