一、基于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. Angular CLI命令

    ng 基础命令 npm install –g @angular/cli npm install -g @angular/cli@latest ng serve –prot –aot 启动项目并压缩项目 ...

  2. WebBrowser获取完整COOKIE

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern bool ...

  3. _event_stop

    EventId 事件ID TeamId 事件玩家分组,攻守(防守为1,进攻为2),自定义阵营(_faction表自定义阵营ID),公会(公会guid) StopType 结束事件需要满足的条件,枚举类 ...

  4. hdu 3864 D_num Pollard_rho算法和Miller_Rabin算法

    D_num Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Problem De ...

  5. js全选 反选

    // 全选 反选 allChoose: function (o) { var obj = $.extend(true, { id: "#id", name: "name& ...

  6. Python self,init,对象属性

    self关键字的作用 __init__初始化 # coding=utf-8 支持中文 class Human(object): laugh = 'Ha' def show_laugh(self): p ...

  7. 力扣(LeetCode)520. 检测大写字母

    给定一个单词,你需要判断单词的大写使用是否正确. 我们定义,在以下情况时,单词的大写用法是正确的: 全部字母都是大写,比如"USA". 单词中所有字母都不是大写,比如"l ...

  8. HTML 标记 3 —— 框架

    <frameset cols="80,*" frameborder="no" border="0" framespacing=&quo ...

  9. cyberduck的SSH登录

    1.通过配置SSH秘钥. 2.不点匿名(不要点匿名),如果非要填一个名字的话,你写root就行. 3.书签.

  10. vSphere 扩展硬盘空间

    把所有的snapshot都删除了之后,ssh上去之后,进vmfs目录到client machine的目录. 然后执行下面的方法. 虽然成功了,却没看到有扩展的. 唯一的好处是, vSphone Cli ...