当前位置:   article > 正文

Mybatis 动态SQL - 使用foreach标签查询数据、批量新增、批量修改、删除数据_mybatis批量修改foreach嵌套

mybatis批量修改foreach嵌套

前面我们介绍了使用Mybatis完成数据的增删改查,并且也了解了如何在Mybatis中使用JDK的日志系统打印日志;本篇我们介绍使用Mybatis的动态SQL完成查询数据、批量新增、批量修改、删除数据。

如果您对数据的增删改查操作和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

一、数据准备

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

  1. -- 如果数据库不存在则创建数据库
  2. CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
  3. -- 切换数据库
  4. USE demo;
  5. -- 创建用户表
  6. CREATE TABLE IF NOT EXISTS T_USER(
  7. ID INT PRIMARY KEY,
  8. USERNAME VARCHAR(32) NOT NULL,
  9. AGE INT NOT NULL
  10. );
  11. -- 插入用户数据
  12. INSERT INTO T_USER(ID, USERNAME, AGE)
  13. VALUES(1, '张三', 20),(2, '李四', 22),(3, '王五', 24);

创建了一个名称为demo的数据库;并在库里创建了名称为T_USER的用户表并向表中插入了数据

二、环境搭建

1、创建实体类

在cn.horse.demo下创建UserInfo类

UserInfo类:

  1. package cn.horse.demo;
  2. public class UserInfo {
  3. private Integer id;
  4. private String name;
  5. private Integer age;
  6. public UserInfo() { }
  7. public UserInfo(Integer id, String name, Integer age) {
  8. this.id = id;
  9. this.name = name;
  10. this.age = age;
  11. }
  12. public void setId(Integer id) {
  13. this.id = id;
  14. }
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setAge(Integer age) {
  25. this.age = age;
  26. }
  27. public Integer getAge() {
  28. return age;
  29. }
  30. @Override
  31. public String toString() {
  32. StringBuilder stringBuilder = new StringBuilder();
  33. stringBuilder.append('{');
  34. stringBuilder.append("id: " + this.id);
  35. stringBuilder.append(", ");
  36. stringBuilder.append("name: " + this.name);
  37. stringBuilder.append(", ");
  38. stringBuilder.append("age: " + this.age);
  39. stringBuilder.append('}');
  40. return stringBuilder.toString();
  41. }
  42. }

2、Mapper配置文件

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

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="cn.horse.demo.UserInfoMapper">
  6. <select id="findAll" resultType="cn.horse.demo.UserInfo">
  7. SELECT
  8. ID,
  9. USERNAME name,
  10. AGE
  11. FROM T_USER
  12. </select>
  13. </mapper>

3、引入配置文件

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

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <setting name="logImpl" value="JDK_LOGGING"/>
  8. </settings>
  9. <environments default="development">
  10. <environment id="development">
  11. <transactionManager type="JDBC"/>
  12. <dataSource type="POOLED">
  13. <property name="driver" value="org.gjt.mm.mysql.Driver"/>
  14. <property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;useSSL=false&amp;characterEncoding=utf8"/>
  15. <property name="username" value="root"/>
  16. <property name="password" value="horse"/>
  17. </dataSource>
  18. </environment>
  19. </environments>
  20. <mappers>
  21. <mapper resource="demo/UserInfoMapper.xml" />
  22. </mappers>
  23. </configuration>

4、会话工具类

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

  1. package cn.horse.demo;
  2. import org.apache.ibatis.session.SqlSession;
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  5. import java.io.InputStream;
  6. import java.util.Objects;
  7. public class SqlSessionUtils {
  8. private static final SqlSessionFactory sqlSessionFactory;
  9. static {
  10. // 读取mybatis配置文件
  11. InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
  12. // 根据配置创建SqlSession工厂
  13. sqlSessionFactory = new SqlSessionFactoryBuilder()
  14. .build(inputStream);
  15. }
  16. /**
  17. * 开启会话
  18. * @return
  19. */
  20. public static SqlSession openSession() {
  21. return sqlSessionFactory.openSession();
  22. }
  23. /**
  24. * 关闭会话
  25. * @param sqlSession
  26. */
  27. public static void closeSession(SqlSession sqlSession) {
  28. if(Objects.nonNull(sqlSession)) {
  29. sqlSession.close();
  30. }
  31. }
  32. }

5、JDK 日志系统配置

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

  1. handlers=java.util.logging.ConsoleHandler
  2. .level=INFO
  3. cn.horse.demo.UserInfoMapper.level=FINER
  4. java.util.logging.ConsoleHandler.level=ALL
  5. java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
  6. 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类:

  1. package cn.horse.demo;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.logging.LogManager;
  5. public class JdkLogConfig {
  6. public JdkLogConfig() {
  7. try {
  8. InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
  9. LogManager.getLogManager().readConfiguration(inputStream);
  10. } catch (IOException e) {
  11. throw new RuntimeException(e);
  12. }
  13. }
  14. }

6、启动程序

  1. package cn.horse.demo;
  2. import org.apache.ibatis.session.SqlSession;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. public class Main {
  6. public static void main(String[] args) {
  7. // 引入JDK日志配置
  8. System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
  9. find("cn.horse.demo.UserInfoMapper.findAll", null);
  10. }
  11. private static void find(String statement, Object parameter) {
  12. SqlSession sqlSession = null;
  13. try {
  14. sqlSession = SqlSessionUtils.openSession();
  15. List<UserInfo> userInfoList = sqlSession.selectList(statement, parameter);
  16. for (UserInfo userInfo: userInfoList) {
  17. System.out.println(userInfo);
  18. }
  19. } finally {
  20. SqlSessionUtils.closeSession(sqlSession);
  21. }
  22. }
  23. }

执行后的结果如下:

三、foreach标签

foreach标签用于对数组或可迭代对象的遍历

foreach标签的格式如下:

  1. <foreach collection="" item="" index="" open="" separator="" close="">
  2. </foreach>

collection数组或可迭代对象

item数组中的元素或本次迭代的元素

index数组中的索引或本地迭代的序号

open指定开头的字符串

close指定结尾的字符串

separator迭代之间的分隔符

注意:如果可迭代对象是Map对象(或者Map.Entry对象的集合)时,index是键,item是值

四、使用foreach批量插入

在UserInfoMapper.xml配置文件中新增insert标签,并写入insert语句:

  1. <insert id="insert">
  2. INSERT INTO T_USER(ID,
  3. USERNAME,
  4. AGE)
  5. VALUES
  6. <foreach collection="list" item="userInfo" separator=",">
  7. (#{userInfo.id}, #{userInfo.name}, #{userInfo.age})
  8. </foreach>
  9. </insert>

在启动程序中新建batchInsert方法

  1. private static void batchInsert(List<UserInfo> userInfoList) {
  2. SqlSession sqlSession = null;
  3. try {
  4. sqlSession = SqlSessionUtils.openSession();
  5. sqlSession.insert("cn.horse.demo.UserInfoMapper.insert", userInfoList);
  6. sqlSession.commit();
  7. } finally {
  8. SqlSessionUtils.closeSession(sqlSession);
  9. }
  10. }

调用batchInsert方法插入数据,并查询

  1. List<UserInfo> userInfoList = new ArrayList<>();
  2. userInfoList.add(new UserInfo(11, "张三1", 20));
  3. userInfoList.add(new UserInfo(12, "李四1", 22));
  4. userInfoList.add(new UserInfo(13, "王五1", 24));
  5. batchInsert(userInfoList);
  6. find("cn.horse.demo.UserInfoMapper.findAll", null);

执行后的结果如下:

五、使用foreach查询数据

foreach标签常用于构建IN条件语句;

在UserInfoMapper.xml配置文件中新增select标签:

  1. <select id="findByIdList" resultType="cn.horse.demo.UserInfo">
  2. SELECT
  3. ID,
  4. USERNAME name,
  5. AGE
  6. FROM T_USER
  7. <where>
  8. ID IN
  9. <foreach collection="list" item="id" open="(" separator="," close=")">
  10. #{id}
  11. </foreach>
  12. </where>
  13. </select>

查询数据

find("cn.horse.demo.UserInfoMapper.findByIdList", Arrays.asList(11, 12, 13));

执行后的结果如下:

六、使用foreach批量修改

在UserInfoMapper.xml配置文件中新增update标签,并写入update语句:

  1. <update id="update">
  2. <foreach collection="list" item="userInfo" separator=";" close=";">
  3. UPDATE T_USER
  4. <set>
  5. <if test="null != userInfo.name and '' != userInfo.name">
  6. USERNAME = #{userInfo.name},
  7. </if>
  8. <if test="null != userInfo.age">
  9. AGE = #{userInfo.age},
  10. </if>
  11. </set>
  12. WHERE ID = #{userInfo.id}
  13. </foreach>
  14. </update>

在启动程序中新建batchUpdate方法:

  1. private static void batchUpdate(List<UserInfo> userInfoList) {
  2. SqlSession sqlSession = null;
  3. try {
  4. sqlSession = SqlSessionUtils.openSession();
  5. sqlSession.update("cn.horse.demo.UserInfoMapper.update", userInfoList);
  6. sqlSession.commit();
  7. } finally {
  8. SqlSessionUtils.closeSession(sqlSession);
  9. }
  10. }

调用batchUpdate方法更新数据,并查询

  1. List<UserInfo> userInfoList = new ArrayList<>();
  2. userInfoList.add(new UserInfo(11, "张三2", null));
  3. userInfoList.add(new UserInfo(12, "李四2", 30));
  4. userInfoList.add(new UserInfo(13, "王五2", null));
  5. batchUpdate(userInfoList);
  6. find("cn.horse.demo.UserInfoMapper.findByIdList", Arrays.asList(11, 12, 13));

执行后的结果如下:

  1. 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 = ? ;
  2. 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)
  3. Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
  4. ### 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
  5. SET USERNAME = '李四2',
  6. ' at line 5
  7. ### The error may involve defaultParameterMap
  8. ### The error occurred while setting parameters
  9. ### SQL: UPDATE T_USER SET USERNAME = ? WHERE ID = ? ; UPDATE T_USER SET USERNAME = ?, AGE = ? WHERE ID = ? ; UPDATE T_USER SET USERNAME = ? WHERE ID = ? ;
  10. ### 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
  11. SET USERNAME = '李四2',
  12. ' at line 5
  13. at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
  14. at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:200)
  15. at cn.horse.demo.Main.batchUpdate(Main.java:48)
  16. at cn.horse.demo.Main.main(Main.java:29)
  17. 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
  18. SET USERNAME = '李四2',
  19. ' at line 5
  20. at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  21. at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
  22. at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  23. at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
  24. at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
  25. at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
  26. at com.mysql.jdbc.Util.getInstance(Util.java:386)
  27. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
  28. at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933)
  29. at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869)
  30. at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
  31. at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2675)
  32. at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
  33. at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1915)
  34. at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1254)
  35. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  36. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
  37. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  38. at java.base/java.lang.reflect.Method.invoke(Method.java:568)
  39. at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
  40. at jdk.proxy3/jdk.proxy3.$Proxy3.execute(Unknown Source)
  41. at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:46)
  42. at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74)
  43. at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50)
  44. at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
  45. at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
  46. at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:198)
  47. ... 2 more

从上面执行的情况来看,SQL执行过程中报错了,原因是我们批量更新使用的是同时执行多条更新语句,而JDBC是不支持的;解决方式是在JDBC连接中添加连接属性allowMultiQueries=true

修改mybatis-config.xml配置文件:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <setting name="logImpl" value="JDK_LOGGING"/>
  8. </settings>
  9. <environments default="development">
  10. <environment id="development">
  11. <transactionManager type="JDBC"/>
  12. <dataSource type="POOLED">
  13. <property name="driver" value="org.gjt.mm.mysql.Driver"/>
  14. <property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;useSSL=false&amp;characterEncoding=utf8&amp;allowMultiQueries=true"/>
  15. <property name="username" value="root"/>
  16. <property name="password" value="horse"/>
  17. </dataSource>
  18. </environment>
  19. </environments>
  20. <mappers>
  21. <mapper resource="demo/UserInfoMapper.xml" />
  22. </mappers>
  23. </configuration>

在配置文件中我们仅修改了jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true

再次执行后的结果如下:

七、使用foreach批量删除

在UserInfoMapper.xml配置文件中新增delete标签,并写入delete语句:

  1. <delete id="delete">
  2. DELETE FROM T_USER
  3. <where>
  4. ID IN
  5. <foreach collection="list" item="id" open="(" separator="," close=")">
  6. #{id}
  7. </foreach>
  8. </where>
  9. </delete>

在启动程序中新建batchDelete方法:

  1. private static void batchDelete(List<Integer> idList) {
  2. SqlSession sqlSession = null;
  3. try {
  4. sqlSession = SqlSessionUtils.openSession();
  5. sqlSession.delete("cn.horse.demo.UserInfoMapper.delete", idList);
  6. sqlSession.commit();
  7. } finally {
  8. SqlSessionUtils.closeSession(sqlSession);
  9. }
  10. }

调用batchDelete方法更新数据,并查询

  1. batchDelete(Arrays.asList(11, 12, 13));
  2. find("cn.horse.demo.UserInfoMapper.findByIdList", Arrays.asList(11, 12, 13));

执行后的结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/749005
推荐阅读
相关标签
  

闽ICP备14008679号