上一篇我们介绍了在Mybatis映射器的映射方法中使用@Param接收多个参数;本篇我们继续介绍如何在Mybatis的映射器中使用动态SQL。
如果您对Mybatis映射器的映射方法中使用@Param接收多个参数不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis 映射器中映射方法接受多个参数(@Param)https://blog.csdn.net/m1729339749/article/details/133063604
一、数据准备
这里我们直接使用脚本初始化数据库中的数据
-- 如果数据库不存在则创建数据库
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切换数据库
USE demo;
-- 创建用户表
CREATE TABLE IF NOT EXISTS T_USER(ID INT PRIMARY KEY,USERNAME VARCHAR(32) NOT NULL,AGE INT NOT NULL
);
-- 插入用户数据
INSERT INTO T_USER(ID, USERNAME, AGE)
VALUES(1, '张三', 20),(2, '李四', 22),(3, '王五', 24);
创建了一个名称为demo的数据库;并在库里创建了名称为T_USER的用户表并向表中插入了数据
二、创建实体类
在cn.horse.demo下创建UserInfo、UserInfoQuery类
UserInfo类:
package cn.horse.demo;public class UserInfo {private Integer id;private String name;private Integer age;public void setId(Integer id) {this.id = id;}public Integer getId() {return id;}public void setName(String name) {this.name = name;}public String getName() {return name;}public void setAge(Integer age) {this.age = age;}public Integer getAge() {return age;}@Overridepublic String toString() {StringBuilder stringBuilder = new StringBuilder();stringBuilder.append('{');stringBuilder.append("id: " + this.id);stringBuilder.append(", ");stringBuilder.append("name: " + this.name);stringBuilder.append(", ");stringBuilder.append("age: " + this.age);stringBuilder.append('}');return stringBuilder.toString();}
}
UserInfoQuery类:
package cn.horse.demo;public class UserInfoQuery {private Integer startAge;private Integer endAge;public void setStartAge(Integer startAge) {this.startAge = startAge;}public Integer getStartAge() {return startAge;}public void setEndAge(Integer endAge) {this.endAge = endAge;}public Integer getEndAge() {return endAge;}
}
三、创建UserInfoMapper映射器、UserInfoSqlProvider类
在cn.horse.demo下创建UserInfoMapper接口、UserInfoSqlProvider类
UserInfoMapper接口:
package cn.horse.demo;import org.apache.ibatis.annotations.*;import java.util.List;public interface UserInfoMapper {
}
UserInfoSqlProvider类:
package cn.horse.demo;import org.apache.ibatis.annotations.Param;import java.util.*;public class UserInfoSqlProvider {
}
四、引入配置文件
在resources下新建mybatis-config.xml配置文件,并引入UserInfoMapper映射器。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="logImpl" value="JDK_LOGGING"/></settings><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="org.gjt.mm.mysql.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8"/><property name="username" value="root"/><property name="password" value="horse"/></dataSource></environment></environments><mappers><mapper class="cn.horse.demo.UserInfoMapper" /></mappers>
</configuration>
这里我们使用mapper引入映射器,只需要设置class属性为UserInfoMapper接口的全限类名。
五、启动程序配置
1、会话工具类
在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();}}
}
2、JDK 日志系统配置
在resources的目录下新建logging.properties配置文件
handlers=java.util.logging.ConsoleHandler
.level=INFOcn.horse.demo.UserInfoMapper.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);}}
}
3、启动程序配置
package cn.horse.demo;import org.apache.ibatis.session.SqlSession;import java.util.List;
import java.util.function.Consumer;public class Main {public static void main(String[] args) {// 引入JDK日志配置System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");}private static void execute(Consumer<UserInfoMapper> function) {SqlSession sqlSession = null;try {sqlSession = SqlSessionUtils.openSession();function.accept(sqlSession.getMapper(UserInfoMapper.class));sqlSession.commit();} finally {SqlSessionUtils.closeSession(sqlSession);}}
}
execute方法用于执行操作,方法中使用sqlSession.getMapper方法获取映射器对象,然后将映射器对象具体的执行操作委托给了Consumer对象。
六、查询数据
在UserInfoMapper映射器中新增find方法
@SelectProvider(type = UserInfoSqlProvider.class, method = "select")
List<UserInfo> find(@Param("query") UserInfoQuery query);
使用SelectProvider注解,将查询语句的提供者配置成UserInfoSqlProvider的select方法,保证find方法的参数与UserInfoSqlProvider的select方法的参数保持一致(包括@Param注解),以避免出现问题。
在UserInfoSqlProvider中新增select方法
public String select(@Param("query") UserInfoQuery query) {StringBuilder sqlBuilder = new StringBuilder();sqlBuilder.append("SELECT ID, USERNAME name, AGE FROM T_USER");// 获取条件语句List<String> conditionStmt = fetchConditionStatement(query);if(!conditionStmt.isEmpty()) {sqlBuilder.append(" WHERE ");sqlBuilder.append(String.join(" AND ", conditionStmt));}return sqlBuilder.toString();
}// 获取条件语句
private List<String> fetchConditionStatement(UserInfoQuery query) {if(Objects.isNull(query)|| (Objects.isNull(query.getStartAge()) && Objects.isNull(query.getEndAge()))) {return Collections.emptyList();}List<String> conditionStmt = new ArrayList<>(2);if(Objects.nonNull(query.getStartAge())) {conditionStmt.add("AGE >= #{query.startAge}");}if(Objects.nonNull(query.getEndAge())) {conditionStmt.add("AGE <= #{query.endAge}");}return conditionStmt;
}
调用映射器中的find方法查询数据
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");// 查询
execute((UserInfoMapper userInfoMapper) -> {UserInfoQuery query = new UserInfoQuery();query.setEndAge(20);List<UserInfo> userInfoList = userInfoMapper.find(query);for (UserInfo userInfo: userInfoList) {System.out.println(userInfo);}
});
执行后的结果如下:
七、批量新增数据
在UserInfoMapper映射器中新增insert方法
@InsertProvider(type = UserInfoSqlProvider.class, method = "insert")
Integer insert(@Param("userInfoList") List<UserInfo> userInfoList);
使用InsertProvider注解,将新增语句的提供者配置成UserInfoSqlProvider的insert方法,保证insert方法的参数与UserInfoSqlProvider的insert方法的参数保持一致(包括@Param注解),以避免出现问题。
在UserInfoSqlProvider中新增insert方法
public String insert(@Param("userInfoList") List<UserInfo> userInfoList) {StringBuilder sqlBuilder = new StringBuilder("INSERT INTO T_USER(ID, USERNAME, AGE) VALUES");for (int i = 0; i < userInfoList.size(); i++) {sqlBuilder.append('(');sqlBuilder.append("#{userInfoList["+ i +"].id},");sqlBuilder.append("#{userInfoList["+ i +"].name},");sqlBuilder.append("#{userInfoList["+ i +"].age}");sqlBuilder.append(')');if(i != userInfoList.size() - 1) {sqlBuilder.append(',');}}return sqlBuilder.toString();
}
调用映射器中的insert方法新增数据
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");// 插入
execute((UserInfoMapper userInfoMapper) -> {List<UserInfo> userInfoList = new ArrayList<>();UserInfo userInfo1 = new UserInfo();userInfo1.setId(5);userInfo1.setName("王五1");userInfo1.setAge(5);userInfoList.add(userInfo1);UserInfo userInfo2 = new UserInfo();userInfo2.setId(6);userInfo2.setName("王五2");userInfo2.setAge(6);userInfoList.add(userInfo2);Integer total = userInfoMapper.insert(userInfoList);System.out.println("插入条数: " + total);
});
执行后的结果如下:
八、批量修改数据
在UserInfoMapper映射器中新增update方法
@UpdateProvider(type = UserInfoSqlProvider.class, method = "update")
Integer update(@Param("userInfoList") List<UserInfo> userInfoList);
使用UpdateProvider注解,将更新语句的提供者配置成UserInfoSqlProvider的update方法,保证update方法的参数与UserInfoSqlProvider的update方法的参数保持一致(包括@Param注解),以避免出现问题。
在UserInfoSqlProvider中新增update方法
public String update(@Param("userInfoList") List<UserInfo> userInfoList) {StringBuilder sqlBuilder = new StringBuilder();for (int i = 0; i < userInfoList.size(); i++) {sqlBuilder.append("UPDATE T_USER SET ");// 获取条件语句sqlBuilder.append(String.join(", ", fetchUpdateStatement(i, userInfoList.get(i))));sqlBuilder.append(" WHERE ID = #{userInfoList["+ i +"].id}");if(i != userInfoList.size() - 1) {sqlBuilder.append(';');}}return sqlBuilder.toString();
}private List<String> fetchUpdateStatement(Integer i, UserInfo userInfo) {if(Objects.isNull(userInfo)|| (Objects.isNull(userInfo.getName()) && Objects.isNull(userInfo.getAge()))) {return Arrays.asList("ID = #{userInfoList["+ i +"].id}");}List<String> updateStmt = new ArrayList<>(2);if(Objects.nonNull(userInfo.getName())) {updateStmt.add("USERNAME = #{userInfoList["+ i +"].name}");}if(Objects.nonNull(userInfo.getAge())) {updateStmt.add("AGE = #{userInfoList["+ i +"].age}");}return updateStmt;
}
调用映射器中的update方法修改数据
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");// 更新
execute((UserInfoMapper userInfoMapper) -> {List<UserInfo> userInfoList = new ArrayList<>();UserInfo userInfo1 = new UserInfo();userInfo1.setId(5);userInfo1.setName("王五11");userInfoList.add(userInfo1);UserInfo userInfo2 = new UserInfo();userInfo2.setId(6);userInfo2.setAge(26);userInfoList.add(userInfo2);Integer total = userInfoMapper.update(userInfoList);System.out.println("更新条数: " + total);
});
执行后的结果如下:
可能出现的问题:
2023-09-15 14:18:10.601 详细 cn.horse.demo.UserInfoMapper.update - ==> Preparing: UPDATE T_USER SET USERNAME = ? WHERE ID = ?;UPDATE T_USER SET AGE = ? WHERE ID = ?
2023-09-15 14:18:10.641 详细 cn.horse.demo.UserInfoMapper.update - ==> Parameters: 王五11(String), 5(Integer), 26(Integer), 6(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 'UPDATE T_USER SET AGE = 26 WHERE ID = 6' at line 1
### The error may involve cn.horse.demo.UserInfoMapper.update-Inline
### The error occurred while setting parameters
### SQL: UPDATE T_USER SET USERNAME = ? WHERE ID = ?;UPDATE T_USER SET AGE = ? 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 'UPDATE T_USER SET AGE = 26 WHERE ID = 6' at line 1at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:200)at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:62)at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)at jdk.proxy2/jdk.proxy2.$Proxy7.update(Unknown Source)at cn.horse.demo.Main.lambda$main$0(Main.java:59)at cn.horse.demo.Main.execute(Main.java:76)at cn.horse.demo.Main.main(Main.java:49)
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 'UPDATE T_USER SET AGE = 26 WHERE ID = 6' at line 1at 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.$Proxy9.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)... 6 more
从上面执行的情况来看,SQL执行过程中报错了,原因是我们批量更新使用的是同时执行多条更新语句,而JDBC是不支持的;
解决办法:
在JDBC连接中添加连接属性allowMultiQueries=true
修改mybatis-config.xml配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="logImpl" value="JDK_LOGGING"/></settings><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="org.gjt.mm.mysql.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true"/><property name="username" value="root"/><property name="password" value="horse"/></dataSource></environment></environments><mappers><mapper class="cn.horse.demo.UserInfoMapper" /></mappers>
</configuration>
在配置文件中我们仅修改了
jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true
九、批量删除数据
在UserInfoMapper映射器中新增delete方法
@DeleteProvider(type = UserInfoSqlProvider.class, method = "delete")
Integer delete(@Param("idList") List<Integer> idList);
使用DeleteProvider注解,将更新语句的提供者配置成UserInfoSqlProvider的delete方法,保证delete方法的参数与UserInfoSqlProvider的delete方法的参数保持一致(包括@Param注解),以避免出现问题。
在UserInfoSqlProvider中新增delete方法
public String delete(@Param("idList") List<Integer> idList) {StringBuilder sqlBuilder = new StringBuilder("DELETE FROM T_USER WHERE ID IN (");for (int i = 0; i < idList.size(); i++) {sqlBuilder.append("#{idList["+ i +"]}");if(i != idList.size() - 1) {sqlBuilder.append(',');}}sqlBuilder.append(')');return sqlBuilder.toString();
}
调用映射器中的delete方法删除数据
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");// 删除
execute((UserInfoMapper userInfoMapper) -> {Integer total = userInfoMapper.delete(Arrays.asList(5, 6));System.out.println("删除条数: " + total);
});
执行后的结果如下: