一、基于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. hdu 2108 Shape of HDU 判断是否为凸多边形

    Shape of HDU Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Pro ...

  2. tensorflow example1

    用tensorflow实现J(w)=w**2-10*w+25的微分结果 import numpy as npimport tensorflow as tf w=tf.Variable(0,dtype= ...

  3. 《剑指offer》第四十八题(最长不含重复字符的子字符串)

    // 面试题48:最长不含重复字符的子字符串 // 题目:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子 // 字符串的长度.假设字符串中只包含从'a'到'z'的字符. #inclu ...

  4. JS 字符串两边截取空白的trim()方法的封装

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. C#中统计一个过程消耗的时间

    使用Unity进行的测试,代码如下: using System.Collections; using System.Collections.Generic; using UnityEngine; us ...

  6. 图片方向 image orientation Exif

    更新 : 2019-01-02 refer https://stackoverflow.com/questions/3129099/how-to-flip-images-horizontally-wi ...

  7. 响应式布局与bootstrap框架

    原文 网页布局方式 1.固定宽度布局:为网页设置一个固定的宽度,通常以px做为长度单位,常见于PC端网页. 2.流式布局:为网页设置一个相对的宽度,通常以百分比做为长度单位. 3.栅格化布局:将网页宽 ...

  8. 荧光激活细胞分选( FACS)

    全称:fluorescence-activated cell sorting 参考: 利用荧光激活细胞分选技术获取荧光蛋白标记肾小球足细胞 荧光激活细胞分离技术在角膜缘干细胞研究中的应用 [求助]急! ...

  9. Linq to XML 增删改查

    Linq to XML同样是对原C#访问XML文件的方法的封装,简化了用xpath进行xml的查询以及增加,修改,删除xml元素的操作.C#访问XML文件的常用类:XmlDocument,XmlEle ...

  10. a gcc 4.2.4 bug(被stos指令累加后%edi作为参数的)

    a gcc 4.2.4 bug(被stos指令累加后%edi作为参数的) * * Ok, now we can initialize the rest of the tty devices and c ...