Mybatis关于mysql批量更新学习
1.概述
对mybatis常用的操作命令做一下总结,数据库基于mysql。后面章节会涉及数据的批量插入、批量更新和更新后返回主键ID等内容。
1.数据库信息
1.1.表结构定义
CREATE TABLE users
(
id
int(11) NOT NULL AUTO_INCREMENT,
NAME
varchar(20) DEFAULT NULL,
age
int(11) DEFAULT NULL,
remark
varchar(200) DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=682 DEFAULT CHARSET=utf8;
1.2.数据库配置db.properties
mysql.driver=com.mysql.jdbc.Driver
需要开启多行执行功能
jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false"
jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&allowMultiQueries=true"
mysql.url=jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
mysql.username=root
mysql.password=123456
1.3.实体类
package com.tech.ability.mybatis.Entity;
/**
-
Created by kikop on 2019/1/17.
*/
public class MyUser {//实体类的属性和表的字段名称一一对应
private int id;
private String name;
private int age;public String getRemark() {
return remark;
}public void setRemark(String remark) {
this.remark = remark;
}private String remark;
public int getId() {
return id;
}public void setId(int id) {
this.id = id;
}public String getName() {
return name;
}public void setName(String name) {
this.name = name;
}public int getAge() {
return age;
}public void setAge(int age) {
this.age = age;
}@Override
public String toString() {
return "MyUser{" +
"age=" + age +
", id=" + id +
", name='" + name + ''' +
", remark='" + remark + ''' +
'}';
}
}
2.mybatis mapper接口文件
package com.tech.ability.mybatis.Mapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.SelectKey;
import org.springframework.data.repository.query.Param;
/**
-
Created by kikop on 2019/5/19.
*/
public interface MyUserMapper {}
3.mybatis sqlmap映射文件
update users
remark='${currentRow.remark}'
where id =#{currentRow.id}
4.mybatis工具类
package com.tech.ability.mybatis;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
- Created by kikop on 2019/5/19.
*/
public class mybatisUtils {
//mybatis核心配置文件
private static final String mybatis_configPath = "mybatisconfig.xml";
/**
* 读取SqlSession
*
* @return
*/
public static SqlSession getSqlSession(ExecutorType execType, boolean isAutoCommit) {
SqlSession sqlSession = null;
try {
//1.读取mybatis的配置文件
//String resource = "mybatisconfig.xml";
//2.构建sqlSession的工厂
//使用类加载器加载 mybatis 的 classspath中配置文件
InputStream inputStream = null;
// InputStream inputStream = mybatisTest.class.getClassLoader().getResourceAsStream(resource);
inputStream = Resources.getResourceAsStream(mybatis_configPath);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.构建sqlSession的工厂
//使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
//Reader reader = Resources.getResourceAsReader(resource);
//SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//3.创建能执行映射文件中sql的sqlSession
// sqlSession = sessionFactory.openSession(isAutoCommit);
sqlSession = sessionFactory.openSession(execType, isAutoCommit);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
/**
* 关闭session(回收连接池必须)
*
* @param session
*/
public static void closeSqlSession(SqlSession session) {
session.close();
}
/**
* 关闭inputStream
*
* @param inputStream
*/
public static void closeInputSream(InputStream inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.测试代码
5.1.测试1
package com.tech.ability.mybatis;
import com.alibaba.fastjson.JSONObject;
import com.tech.ability.mybatis.Entity.MyUser;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
/**
-
Created by kikop on 2019/1/17.
*/
public class mybatisTest {private static final Logger logger = LogManager.getLogger(mybatisTest.class);
/**
* mybatis手动批量更新
*
* @throws Exception
*/
private static void batchUpdateUserInfoListManualTest() throws Exception {
//1.构建sqlSession
SqlSession session = mybatisUtils.getSqlSession(ExecutorType.SIMPLE, false);
//2.映射sql的标识字符串
StringBuffer statement = new StringBuffer();
statement.append("com.tech.ability.mybatis.Mapper.MyUserMapper"); //mapper标签的namespace属性的值
statement.append(".batchUpdateUserInfoList"); //select标签的id属性值
//3.定义查询条件
List idList = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1);
jsonObject.put("remark", "11_remarktest11**--");
idList.add(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("id", 2);
jsonObject.put("remark", "22_remarktest22**--");
idList.add(jsonObject);
JSONObject requestJsonObject = new JSONObject();
requestJsonObject.put("idList", idList);
//4.执行查询返回一个唯一user对象的sql
int updateResult = session.update(statement.toString(), requestJsonObject);
if (updateResult > 0) {
session.commit();
} else {
session.rollback();
}
//5.资源释放(连接池回收)
mybatisUtils.closeSqlSession(session);
}
2019-05-19 16:49:07.672 DEBUG [main][LogFactory.java:124] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2019-05-19 16:49:07.690 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:49:07.691 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:49:07.691 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:49:07.691 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:49:07.881 DEBUG [main][JdbcTransaction.java:129] - Opening JDBC Connection
2019-05-19 16:49:08.316 DEBUG [main][PooledDataSource.java:378] - Created connection 898694235.
2019-05-19 16:49:08.317 DEBUG [main][JdbcTransaction.java:95] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3590fc5b]
2019-05-19 16:49:08.321 DEBUG [main][BaseJdbcLogger.java:132] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@3590fc5b]
2019-05-19 16:49:08.322 DEBUG [main][BaseJdbcLogger.java:132] - ==> Preparing: update users SET remark='11_remarktest11--' where id =? ; update users SET remark='22_remarktest22--' where id =?
2019-05-19 16:49:08.364 DEBUG [main][BaseJdbcLogger.java:132] - ==> Parameters: 1(Integer), 2(Integer)
2019-05-19 16:49:08.373 DEBUG [main][BaseJdbcLogger.java:132] - <== Updates: 1
2019-05-19 16:49:08.374 DEBUG [main][JdbcTransaction.java:66] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3590fc5b]
2019-05-19 16:49:08.411 DEBUG [main][JdbcTransaction.java:117] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3590fc5b]
2019-05-19 16:49:08.412 DEBUG [main][JdbcTransaction.java:85] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3590fc5b]
2019-05-19 16:49:08.412 DEBUG [main][PooledDataSource.java:332] - Returned connection 898694235 to pool.
5.2.测试2
/**
* mybatis自动批量更新
*
* @throws Exception
*/
private static void batchUpdateUserInfoListAutoTest() throws Exception {
//1.构建sqlSession
SqlSession session = mybatisUtils.getSqlSession(ExecutorType.SIMPLE, true);
//2.映射sql的标识字符串
StringBuffer statement = new StringBuffer();
statement.append("com.tech.ability.mybatis.Mapper.MyUserMapper"); //mapper标签的namespace属性的值
statement.append(".batchUpdateUserInfoList"); //select标签的id属性值
//3.定义查询条件
List idList = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1);
jsonObject.put("remark", "1_remark");
idList.add(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("id", 2);
jsonObject.put("remark", "2_remark");
idList.add(jsonObject);
JSONObject requestJsonObject = new JSONObject();
requestJsonObject.put("idList", idList);
//4.执行查询返回一个唯一user对象的sql
int updateResult = session.update(statement.toString(), requestJsonObject);
//5.资源释放(连接池回收)
mybatisUtils.closeSqlSession(session);
}
2019-05-19 16:48:05.561 DEBUG [main][LogFactory.java:124] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2019-05-19 16:48:05.580 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:48:05.581 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:48:05.581 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:48:05.582 DEBUG [main][PooledDataSource.java:304] - PooledDataSource forcefully closed/removed all connections.
2019-05-19 16:48:05.714 DEBUG [main][JdbcTransaction.java:129] - Opening JDBC Connection
2019-05-19 16:48:06.067 DEBUG [main][PooledDataSource.java:378] - Created connection 898694235.
2019-05-19 16:48:06.069 DEBUG [main][BaseJdbcLogger.java:132] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@3590fc5b]
2019-05-19 16:48:06.071 DEBUG [main][BaseJdbcLogger.java:132] - ==> Preparing: update users SET remark='1_remark' where id =? ; update users SET remark='2_remark' where id =?
2019-05-19 16:48:06.152 DEBUG [main][BaseJdbcLogger.java:132] - ==> Parameters: 1(Integer), 2(Integer)
2019-05-19 16:48:06.179 DEBUG [main][BaseJdbcLogger.java:132] - <== Updates: 1
2019-05-19 16:48:06.180 DEBUG [main][JdbcTransaction.java:85] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3590fc5b]
2019-05-19 16:48:06.180 DEBUG [main][PooledDataSource.java:332] - Returned connection 898694235 to pool.
6.调用
public static void main(String[] args) throws Exception {
//getUserInfoByIDTest();
//getUserInfoByInTest();
//getUserInfoByInnerForeachTest();
//batchUpdateUserInfoListManualTest();
//batchUpdateUserInfoListAutoTest();
//batchInsertUserInfoListByUnionAllTest();
//batchInsertUserInfoListByExecutorBachTest2();
//insertUserXmlTest();
batchInsertUserInfoListByUnionAllTest();
}
}
总结
1.数据库连接时,设置运行多行查询。
2.多条语句,用“;”隔开即可。