Mybatis 动态SQL – 使用if,where标签动态生成条件语句

前面几篇我们介绍了使用Mybatis进行数据的增删改查,并且也了解了如何在Mybatis中使用JDK的日志系统打印日志;本篇我们继续介绍如何使用Mybatis提供的if,where标签动态生成条件语句。

如果您对数据的增删改查和Mybatis集成JDK日志系统不太了解,建议您先进行了解后再阅读本篇,可以参考:

Mybatis查询数据icon-default.png?t=N7T8https://blog.csdn.net/m1729339749/article/details/132469672Mybatis 日志(JDK Log)icon-default.png?t=N7T8https://blog.csdn.net/m1729339749/article/details/132565362Mybatis 插入、修改、删除icon-default.png?t=N7T8https://blog.csdn.net/m1729339749/article/details/132601345

一、数据准备

这里我们直接使用脚本初始化数据库中的数据

-- 如果数据库不存在则创建数据库
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切换数据库
USE demo;
-- 创建用户表
CREATE TABLE IF NOT EXISTS T_TEACHER(
  ID INT PRIMARY KEY COMMENT '教师编号',
  TEACHER_NAME VARCHAR(64) NOT NULL COMMENT '教师名称',
  DEPARTMENT VARCHAR(16) NOT NULL COMMENT '所属部门',
  BIRTH DATE NOT NULL COMMENT '出生年月',
  DEGREE VARCHAR(16) NOT NULL COMMENT '学历(ZK:专科, BK:本科, YJS:研究生, BS:博士)'
);
-- 插入用户数据
INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
VALUES(1, '张三1', '001', '1990-06-12', 'BK'),
      (2, '李四1', '002', '1992-05-10', 'BK'),
      (3, '张三2', '003', '1988-01-15', 'YJS'),
      (4, '李四2', '001', '1979-03-10', 'BK'),
      (5, '李四3', '003', '1995-08-16', 'YJS');

创建了一个名称为demo的数据库;并在库里创建了名称为T_TEACHER的教师表并向表中插入了数据

二、环境搭建

1、创建实体类

在cn.horse.demo下创建TeacherInfo实体类:

TeacherInfo类:

package cn.horse.demo;

import java.time.LocalDate;

public class TeacherInfo {
    private Integer id;
    private String name;
    private String department;
    private LocalDate birth;
    private String degree;

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{ ");
        stringBuilder.append("id: ");
        stringBuilder.append(this.id);
        stringBuilder.append(", ");
        stringBuilder.append("name: ");
        stringBuilder.append(this.name);
        stringBuilder.append(", ");
        stringBuilder.append("department: ");
        stringBuilder.append(this.department);
        stringBuilder.append(", ");
        stringBuilder.append("birth: ");
        stringBuilder.append(this.birth);
        stringBuilder.append(", ");
        stringBuilder.append("degree: ");
        stringBuilder.append(this.degree);
        stringBuilder.append(" }");
        return stringBuilder.toString();
    }
}

2、Mapper配置文件

在resources的目录下新建TeacherInfoMapper.xml配置文件





    

3、引入配置文件

在resources下新建mybatis-config.xml配置文件,并引入TeacherInfoMapper.xml配置文件




    
        
    

    
        
            
            
                
                
                
                
            
        
    

    
        
    

4、会话工具类

在cn.horse.demo包下新建SqlSessionUtils工具类

package cn.horse.demo;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Objects;

public class SqlSessionUtils {

    private static final SqlSessionFactory sqlSessionFactory;
    static {
        // 读取mybatis配置文件
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
        // 根据配置创建SqlSession工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);
    }

    /**
     * 开启会话
     * @return
     */
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }

    /**
     * 关闭会话
     * @param sqlSession
     */
    public static void closeSession(SqlSession sqlSession) {
        if(Objects.nonNull(sqlSession)) {
            sqlSession.close();
        }
    }
}

5、JDK 日志系统配置

在resources的目录下新建logging.properties配置文件

handlers=java.util.logging.ConsoleHandler
.level=INFO

cn.horse.demo.TeacherInfoMapper.level=FINER
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tT.%1$tL %4$s %3$s - %5$s%6$s%n

在cn.horse.demo下新建JdkLogConfig类:

JdkLogConfig类:

package cn.horse.demo;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;

public class JdkLogConfig {

    public JdkLogConfig() {
        try {
            InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
            LogManager.getLogManager().readConfiguration(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

6、启动程序

package cn.horse.demo;

import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        // 引入JDK日志配置
        System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

        // 查询所有教师
        findAll("cn.horse.demo.TeacherInfoMapper.findAll", null);
    }

    private static void findAll(String statement, TeacherInfoQuery query) {
        SqlSession sqlSession = null;
        try {
            sqlSession = SqlSessionUtils.openSession();
            List teacherInfoList = sqlSession.selectList(statement, query);
            for (TeacherInfo teacherInfo: teacherInfoList) {
                System.out.println(teacherInfo);
            }
        } finally {
            SqlSessionUtils.closeSession(sqlSession);
        }
    }
}

执行后的结果如下:

Mybatis 动态SQL – 使用if,where标签动态生成条件语句_第1张图片

三、例子:查询学历为本科,部门为001的教师

在TeacherInfoMapper.xml配置文件中新增findByQuery查询语句:


测试:

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("BK");
query.setDepartment("001");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

执行后的结果如下:

四、使用 if 标签避免SQL冗余

这里如果我们需要只查询学历为本科的教师,又该如何来做呢?

如果新增加一个查询标签则会造成大量的SQL语句重复,这里使用if标签就能解决这类问题,可以根据条件动态的拼接SQL语句;

if标签是主要用于进行条件判断,常用于动态生成条件语句、更新语句;当条件满足时,会将if标签中的SQL语句片段拼接到SQL语句中;当条件不满足时,则跳过if标签中的SQL语句片段;


if标签:test的属性值是条件,degree、department是参数,参数可以在标签的属性中直接使用;

第一个条件:degree不为null并且不为空字符串条件才成立

第二个条件:department不为null并且不为空字符串条件才成立

测试:

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

// 查询学历为本科的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("BK");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

结果分析:

degree值为BK, 第一个条件满足,DEGREE = #{degree}会拼接到SQL语句中;department值为null,第二个条件不满足,直接跳过;

最终只有DEGREE = #{degree}拼接到SQL语句中,同样SQL执行日志也与我们分析的结果一致。

五、使用 if 标签可能会导致的AND,WHERE问题

1、查询所有的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

TeacherInfoQuery query = new TeacherInfoQuery();
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

2023-08-31 10:48:39.221 详细 cn.horse.demo.TeacherInfoMapper.findByQuery - ==>  Preparing: SELECT ID, TEACHER_NAME name, DEPARTMENT, BIRTH, DEGREE FROM T_TEACHER WHERE 
2023-08-31 10:48:39.266 详细 cn.horse.demo.TeacherInfoMapper.findByQuery - ==> Parameters: 
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
### The error may exist in demo/TeacherInfoMapper.xml
### The error may involve cn.horse.demo.TeacherInfoMapper.findByQuery-Inline
### The error occurred while setting parameters
### SQL: SELECT             ID,             TEACHER_NAME name,             DEPARTMENT,             BIRTH,             DEGREE         FROM T_TEACHER         WHERE
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
	at cn.horse.demo.Main.findAll(Main.java:45)
	at cn.horse.demo.Main.main(Main.java:32)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
	at com.mysql.jdbc.Util.getInstance(Util.java:386)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2675)
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1915)
	at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1254)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
	at jdk.proxy3/jdk.proxy3.$Proxy3.execute(Unknown Source)
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
	at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
	at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
	at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
	... 3 more

结果分析:

degree值为null, 第一个条件不满足,直接跳过;

department值为null,第一个条件不满足,直接跳过;

最终拼装好的SQL语句会变成

SELECT ID, TEACHER_NAME name, DEPARTMENT, BIRTH, DEGREE FROM T_TEACHER WHERE

多了一个WHERE,与报错的信息一致。

2、查询部门为001的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

// 查询部门为001的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDepartment("001");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

2023-08-30 22:27:12.164 详细 cn.horse.demo.TeacherInfoMapper.findByQuery - ==>  Preparing: SELECT ID, TEACHER_NAME name, DEPARTMENT, BIRTH, DEGREE FROM T_TEACHER WHERE AND DEPARTMENT = ? 
2023-08-30 22:27:12.220 详细 cn.horse.demo.TeacherInfoMapper.findByQuery - ==> Parameters: 001(String)
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND DEPARTMENT = '001'' at line 11
### The error may exist in demo/TeacherInfoMapper.xml
### The error may involve cn.horse.demo.TeacherInfoMapper.findByQuery-Inline
### The error occurred while setting parameters
### SQL: SELECT             ID,             TEACHER_NAME name,             DEPARTMENT,             BIRTH,             DEGREE         FROM T_TEACHER         WHERE                                 AND DEPARTMENT = ?
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND DEPARTMENT = '001'' at line 11
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
	at cn.horse.demo.Main.findAll(Main.java:39)
	at cn.horse.demo.Main.main(Main.java:32)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND DEPARTMENT = '001'' at line 11
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
	at com.mysql.jdbc.Util.getInstance(Util.java:386)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2675)
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1915)
	at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1254)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
	at jdk.proxy3/jdk.proxy3.$Proxy3.execute(Unknown Source)
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
	at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
	at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
	at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
	... 3 more

结果分析:

degree值为null, 第一个条件不满足,直接跳过;

department值为001,第二个条件满足,AND DEPARTMENT = #{department}会拼接到SQL语句中;

最终只有AND DEPARTMENT = #{department}拼接到SQL语句中,最终拼装好的SQL语句会变成

SELECT ID, TEACHER_NAME name, DEPARTMENT, BIRTH, DEGREE FROM T_TEACHER WHERE AND DEPARTMENT = #{department}

多了一个AND,与报错的信息一致。

六、使用恒等式解决AND,WHERE问题

在WHERE后面增加恒等式1=1


1、查询所有的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

TeacherInfoQuery query = new TeacherInfoQuery();
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

Mybatis 动态SQL – 使用if,where标签动态生成条件语句_第2张图片

2、查询部门为001的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

// 查询部门为001的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDepartment("001");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

3、查询学历为本科的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

// 查询学历为本科的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("BK");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

七、使用where标签解决AND,WHERE问题

where标签有两个作用:

(1)判断是否存在条件,如果条件不存在,则不再拼接where;如果条件存在,则拼接where

(2)剔除where后面多余的AND或OR


1、查询所有的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

TeacherInfoQuery query = new TeacherInfoQuery();
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

Mybatis 动态SQL – 使用if,where标签动态生成条件语句_第3张图片

2、查询部门为001的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

// 查询部门为001的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDepartment("001");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

3、查询学历为本科的教师

// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");

// 查询学历为本科的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("BK");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);

查询的结果如下:

你可能感兴趣的:(Mybatis,mybatis,java)