上一篇我们介绍了使用Mybatis提供的if,where标签动态生成条件语句;本篇我们在上一篇的基础上介绍如何使用Mybatis提供的if,set标签动态生成更新语句。
如果您对if,where标签动态生成条件语句不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis 动态SQL – 使用if,where标签动态生成条件语句https://blog.csdn.net/m1729339749/article/details/132627894
这里我们直接使用脚本初始化数据库中的数据
-- 如果数据库不存在则创建数据库
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的教师表并向表中插入了数据
在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;
public void setId(Integer id) {
this.id = id;
}
public void setDepartment(String department) {
this.department = department;
}
public void setDegree(String degree) {
this.degree = 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();
}
}
在resources的目录下新建TeacherInfoMapper.xml配置文件
在resources下新建mybatis-config.xml配置文件,并引入TeacherInfoMapper.xml配置文件
在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();
}
}
}
在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);
}
}
}
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
public class Main {
public static void main(String[] args) {
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
// 查询编号为2的教师
findById("cn.horse.demo.TeacherInfoMapper.findById", 2);
}
private static void findById(String statement, Integer id) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
TeacherInfo teacherInfo = sqlSession.selectOne(statement, id);
System.out.println(teacherInfo);
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
}
执行后的结果如下:
在TeacherInfoMapper.xml配置文件中新增updateByEntity更新标签:
UPDATE T_TEACHER
SET DEPARTMENT = #{department},
DEGREE = #{degree}
WHERE ID = #{id}
在程序中新建静态update方法:
private static void update(String statement, TeacherInfo teacherInfo) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.update(statement, teacherInfo);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
// 更新编号为2的教师
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(2);
teacherInfo.setDepartment("001");
teacherInfo.setDegree("YJS");
update("cn.horse.demo.TeacherInfoMapper.updateByEntity", teacherInfo);
// 查询编号为2的教师
findById("cn.horse.demo.TeacherInfoMapper.findById", 2);
执行后的结果如下:
这里如果我们需要只更新教师的学历,又该如何来做呢?
如果新增加一个更新标签则会造成大量的SQL语句重复,这里使用if标签就能解决这类问题,可以根据条件动态的拼接SQL语句;
if标签是主要用于进行条件判断;当条件满足时,会将if标签中的SQL语句片段拼接到SQL语句中;当条件不满足时,则跳过if标签中的SQL语句片段;常用于动态生成条件语句、更新语句。
UPDATE T_TEACHER
SET
DEPARTMENT = #{department},
DEGREE = #{degree}
WHERE ID = #{id}
if标签:test的属性值是条件,department、degree是参数,参数可以在标签的属性中直接使用;
第一个条件:department不为null并且不为空字符串条件才成立
第二个条件:degree不为null并且不为空字符串条件才成立
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
// 更新编号为2的教师
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(2);
teacherInfo.setDegree("BS");
update("cn.horse.demo.TeacherInfoMapper.updateByEntity", teacherInfo);
// 查询编号为2的教师
findById("cn.horse.demo.TeacherInfoMapper.findById", 2);
查询的结果如下:
结果分析:
department值为null,第一个条件不满足,直接跳过;
degree值为BS, 第二个条件满足,DEGREE = #{degree}会拼接到SQL语句中;
最终只有DEGREE = #{degree}拼接到SQL语句中,同样SQL执行日志也与我们分析的结果一致。
// 引入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-31 21:27:19.850 详细 cn.horse.demo.TeacherInfoMapper.updateByEntity - ==> Preparing: UPDATE T_TEACHER SET DEPARTMENT = ?, WHERE ID = ?
2023-08-31 21:27:19.913 详细 cn.horse.demo.TeacherInfoMapper.updateByEntity - ==> Parameters: 003(String), 2(Integer)
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error updating 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 'WHERE ID = 2' at line 7
### The error may involve cn.horse.demo.TeacherInfoMapper.updateByEntity-Inline
### The error occurred while setting parameters
### SQL: UPDATE T_TEACHER SET DEPARTMENT = ?, WHERE ID = ?
### 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 'WHERE ID = 2' at line 7
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:200)
at cn.horse.demo.Main.update(Main.java:53)
at cn.horse.demo.Main.main(Main.java:44)
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 'WHERE ID = 2' at line 7
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.update(PreparedStatementHandler.java:46)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74)
at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50)
at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:198)
... 2 more
结果分析:
department值为001,第一个条件满足,DEPARTMENT = #{department}, 会拼接到SQL语句中;
degree值为null, 第二个条件不满足,直接跳过;
最终只有DEPARTMENT = #{department}, 拼接到SQL语句中,最终拼装好的SQL语句会变成
UPDATE T_TEACHER SET DEPARTMENT = #{department}, WHERE ID = #{id}
多了一个逗号,与报错的信息一致。
set标签可用于剔除更新语句中多余的逗号
UPDATE T_TEACHER
DEPARTMENT = #{department},
DEGREE = #{degree},
WHERE ID = #{id}
// 更新编号为2的教师
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(2);
teacherInfo.setDepartment("003");
update("cn.horse.demo.TeacherInfoMapper.updateByEntity", teacherInfo);
// 查询编号为2的教师
findById("cn.horse.demo.TeacherInfoMapper.findById", 2);
查询的结果如下:
// 更新编号为2的教师
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(2);
teacherInfo.setDegree("BK");
update("cn.horse.demo.TeacherInfoMapper.updateByEntity", teacherInfo);
// 查询编号为2的教师
findById("cn.horse.demo.TeacherInfoMapper.findById", 2);
查询的结果如下: