前面我们介绍了使用Mybatis完成数据的增删改查,并且也了解了如何在Mybatis中使用JDK的日志系统打印日志;本篇我们介绍使用Mybatis的动态SQL完成查询数据、批量新增、批量修改、删除数据。
如果您对数据的增删改查操作和Mybatis集成JDK日志系统不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis查询数据https://blog.csdn.net/m1729339749/article/details/132469672Mybatis 日志(JDK Log)https://blog.csdn.net/m1729339749/article/details/132565362Mybatis 插入、修改、删除https://blog.csdn.net/m1729339749/article/details/132601345
一、数据准备
这里我们直接使用脚本初始化数据库中的数据
-- 如果数据库不存在则创建数据库
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的用户表并向表中插入了数据
二、环境搭建
1、创建实体类
在cn.horse.demo下创建UserInfo类
UserInfo类:
package cn.horse.demo;
public class UserInfo {
private Integer id;
private String name;
private Integer age;
public UserInfo() { }
public UserInfo(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = 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;
}
@Override
public 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();
}
}
2、Mapper配置文件
在resources的目录下新建UserInfoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.UserInfoMapper">
<select id="findAll" resultType="cn.horse.demo.UserInfo">
SELECT
ID,
USERNAME name,
AGE
FROM T_USER
</select>
</mapper>
3、引入配置文件
在resources下新建mybatis-config.xml配置文件,并引入UserInfoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//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 resource="demo/UserInfoMapper.xml" />
</mappers>
</configuration>
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.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);
}
}
}
6、启动程序
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import java.util.ArrayList;
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");
find("cn.horse.demo.UserInfoMapper.findAll", null);
}
private static void find(String statement, Object parameter) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
List<UserInfo> userInfoList = sqlSession.selectList(statement, parameter);
for (UserInfo userInfo: userInfoList) {
System.out.println(userInfo);
}
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
}
执行后的结果如下:
三、foreach标签
foreach标签用于对数组或可迭代对象的遍历
foreach标签的格式如下:
<foreach collection="" item="" index="" open="" separator="" close="">
</foreach>
collection:数组或可迭代对象
item:数组中的元素或本次迭代的元素
index:数组中的索引或本地迭代的序号
open:指定开头的字符串
close:指定结尾的字符串
separator:迭代之间的分隔符
注意:如果可迭代对象是Map对象(或者Map.Entry对象的集合)时,index是键,item是值
四、使用foreach批量插入
在UserInfoMapper.xml配置文件中新增insert标签,并写入insert语句:
<insert id="insert">
INSERT INTO T_USER(ID,
USERNAME,
AGE)
VALUES
<foreach collection="list" item="userInfo" separator=",">
(#{userInfo.id}, #{userInfo.name}, #{userInfo.age})
</foreach>
</insert>
在启动程序中新建batchInsert方法
private static void batchInsert(List<UserInfo> userInfoList) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.insert("cn.horse.demo.UserInfoMapper.insert", userInfoList);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
调用batchInsert方法插入数据,并查询
List<UserInfo> userInfoList = new ArrayList<>();
userInfoList.add(new UserInfo(11, "张三1", 20));
userInfoList.add(new UserInfo(12, "李四1", 22));
userInfoList.add(new UserInfo(13, "王五1", 24));
batchInsert(userInfoList);
find("cn.horse.demo.UserInfoMapper.findAll", null);
执行后的结果如下:
五、使用foreach查询数据
foreach标签常用于构建IN条件语句;
在UserInfoMapper.xml配置文件中新增select标签:
<select id="findByIdList" resultType="cn.horse.demo.UserInfo">
SELECT
ID,
USERNAME name,
AGE
FROM T_USER
<where>
ID IN
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</select>
查询数据
find("cn.horse.demo.UserInfoMapper.findByIdList", Arrays.asList(11, 12, 13));
执行后的结果如下:
六、使用foreach批量修改
在UserInfoMapper.xml配置文件中新增update标签,并写入update语句:
<update id="update">
<foreach collection="list" item="userInfo" separator=";" close=";">
UPDATE T_USER
<set>
<if test="null != userInfo.name and '' != userInfo.name">
USERNAME = #{userInfo.name},
</if>
<if test="null != userInfo.age">
AGE = #{userInfo.age},
</if>
</set>
WHERE ID = #{userInfo.id}
</foreach>
</update>
在启动程序中新建batchUpdate方法:
private static void batchUpdate(List<UserInfo> userInfoList) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.update("cn.horse.demo.UserInfoMapper.update", userInfoList);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
调用batchUpdate方法更新数据,并查询
List<UserInfo> userInfoList = new ArrayList<>();
userInfoList.add(new UserInfo(11, "张三2", null));
userInfoList.add(new UserInfo(12, "李四2", 30));
userInfoList.add(new UserInfo(13, "王五2", null));
batchUpdate(userInfoList);
find("cn.horse.demo.UserInfoMapper.findByIdList", Arrays.asList(11, 12, 13));
执行后的结果如下:
2023-09-03 10:28:11.873 详细 cn.horse.demo.UserInfoMapper.update - ==> Preparing: UPDATE T_USER SET USERNAME = ? WHERE ID = ? ; UPDATE T_USER SET USERNAME = ?, AGE = ? WHERE ID = ? ; UPDATE T_USER SET USERNAME = ? WHERE ID = ? ;
2023-09-03 10:28:11.909 详细 cn.horse.demo.UserInfoMapper.update - ==> Parameters: 张三2(String), 11(Integer), 李四2(String), 30(Integer), 12(Integer), 王五2(String), 13(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 USERNAME = '李四2',
' at line 5
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: UPDATE T_USER SET USERNAME = ? WHERE ID = ? ; UPDATE T_USER SET USERNAME = ?, AGE = ? WHERE ID = ? ; UPDATE T_USER SET USERNAME = ? 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 USERNAME = '李四2',
' at line 5
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.batchUpdate(Main.java:48)
at cn.horse.demo.Main.main(Main.java:29)
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 USERNAME = '李四2',
' at line 5
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
从上面执行的情况来看,SQL执行过程中报错了,原因是我们批量更新使用的是同时执行多条更新语句,而JDBC是不支持的;解决方式是在JDBC连接中添加连接属性allowMultiQueries=true
修改mybatis-config.xml配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//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 resource="demo/UserInfoMapper.xml" />
</mappers>
</configuration>
在配置文件中我们仅修改了jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true
再次执行后的结果如下:
七、使用foreach批量删除
在UserInfoMapper.xml配置文件中新增delete标签,并写入delete语句:
<delete id="delete">
DELETE FROM T_USER
<where>
ID IN
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</delete>
在启动程序中新建batchDelete方法:
private static void batchDelete(List<Integer> idList) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.delete("cn.horse.demo.UserInfoMapper.delete", idList);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
调用batchDelete方法更新数据,并查询
batchDelete(Arrays.asList(11, 12, 13));
find("cn.horse.demo.UserInfoMapper.findByIdList", Arrays.asList(11, 12, 13));
执行后的结果如下: