springboot mybatis 批量insert 操作

直接上代码:

1.首先要在pom.xml中导入包:

springboot 1.5.8

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 使用数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.25</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version>
</dependency>

2.springboot mybatis配置:

package com.xxx.common.config;

@Configuration
@MapperScan(basePackages="com.xxx.mapper")
public class MyBatisConfig { @Autowired
private Environment env; /**
* 创建数据源
* @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错
*/
@Bean
//@Primary
public DataSource getDataSource() throws Exception{
Properties props = new Properties();
props.put("driverClassName", env.getProperty("jdbc.driverClassName"));
props.put("url", env.getProperty("jdbc.url"));
props.put("username", env.getProperty("jdbc.username"));
props.put("password", env.getProperty("jdbc.password"));
return DruidDataSourceFactory.createDataSource(props);
}
@Bean
public PlatformTransactionManager txManager() throws Exception {
return new DataSourceTransactionManager(getDataSource());
} /**
* 根据数据源创建SqlSessionFactory
*/
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
fb.setDataSource(ds);//指定数据源(这个必须有,否则报错)
fb.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
//下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加
fb.setTypeAliasesPackage(env.getProperty("mybatis.basePackage"));//指定基包
fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));//指定xml文件位置 return fb.getObject();
} @Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

3.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="cacheEnabled" value="true"/>
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->
<setting name="aggressiveLazyLoading" value="true"/>
<!-- 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default:true -->
<setting name="multipleResultSetsEnabled" value="true"/>
<!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true -->
<setting name="useColumnLabel" value="true"/>
<!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false -->
<setting name="useGeneratedKeys" value="true"/>
<!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分 FULL:全部 -->
<setting name="autoMappingBehavior" value="PARTIAL"/>
<!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) -->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!-- 使用驼峰命名法转换字段。 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->
<setting name="localCacheScope" value="SESSION"/>
<!-- 设置但JDBC类型为空时,某些驱动程序 要指定值,default:OTHER,插入空值时不需要指定类型 -->
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="logImpl" value="LOG4J2"/>
<!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
<property name="offsetAsPageNum" value="false"/>
<property name="rowBoundsWithCount" value="false"/>
<property name="pageSizeZero" value="true"/>
<property name="reasonable" value="false"/>
<property name="supportMethodsArguments" value="false"/>
<property name="returnPageInfo" value="none"/>
</plugin>
</plugins>
</configuration>

4.application.yml:

server:
port: 8080
context-path: /test
tomcat:
max-threads: 800 #dev
jdbc:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
username: root
password: 123456 #mybatis config
mybatis:
basePackage: com.xxx.model
mapperLocations: classpath*:/mapper/**/*.xml

5.java model:

package com.xxx.model;

/**
* 实体类对应的数据表为: aaa
* @author Jeff
* @date 2017-11-09 14:28:47
*/ public class IotBasRunType222 { private Integer runType; private String name; private String nameEn; //省略get set。。。
}

6.java mapper:

package com.xxx.mapper;

public interface IotBasRunTypeMapper222  {
int insertBatch(List<IotBasRunType222 > iotBasRunTypeList);
}

7.xml mapper:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxx.mapper.IotBasRunTypeMapper222" > <sql id="Base_Column_List" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
net_type, t_name, name_en
</sql> <insert id="insertBatch" parameterType="java.util.List">
insert into aaa (<include refid="Base_Column_List" />)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.runType,jdbcType=INTEGER}, #{item.name,jdbcType=VARCHAR}, #{item.nameEn,jdbcType=VARCHAR})
</foreach>
</insert>
</mapper> #如果要设置默认值,可以采用如下方式: <insert id="insertBatch" parameterType="java.util.List">
insert into xxx (<include refid="Base_Column_List" />)
values
<foreach collection="list" item="item" index="index" separator=",">
<trim prefix=" (" suffix=")" suffixOverrides="," >
#{item.deviceType,jdbcType=SMALLINT}, #{item.deviceModel,jdbcType=SMALLINT}, <choose>
<when test="item.delayTime != null">
#{item.delayTime,jdbcType=INTEGER},
</when>
<otherwise>
0,
</otherwise>
</choose>
<choose>
<when test="item.delaycanceTime != null">
#{item.delaycanceTime,jdbcType=INTEGER},
</when>
<otherwise>
0,
</otherwise>
</choose>
<choose>
<when test="item.delta != null">
#{item.delta,jdbcType=DOUBLE},
</when>
<otherwise>
0,
</otherwise>
</choose> </trim>
</foreach>
</insert>

8.service imp:

package com.xxx.service.impl;

/**
* @desc
* @author create author by deer
* @date 2017年11月28日上午9:41:18
*/
@Service
public class IotBasRunType222ServiceImpl extends IotBaseServiceImpl<IotBasRunType222>{
@Autowired
private SqlSessionTemplate sqlSessionTemplate; public boolean insertBatch(List<IotBasRunType222> members)
throws Exception {
// TODO Auto-generated method stub
int result = 1;
SqlSession batchSqlSession = null;
try {
batchSqlSession = this.sqlSessionTemplate
.getSqlSessionFactory()
.openSession(ExecutorType.BATCH, false);// 获取批量方式的sqlsession
//通过新的session获取mapper
IotBasRunTypeMapper222 mapper = batchSqlSession.getMapper(IotBasRunTypeMapper222.class); //int batchCount = 1000;// 每批commit的个数
int batchCount = 10;// 每批commit的个数
int batchLastIndex = batchCount;// 每批最后一个的下标 for (int index = 0; index < members.size();) {
if (batchLastIndex >= members.size()) {
batchLastIndex = members.size(); result = result + mapper.insertBatch(members.subList(index, batchLastIndex));
batchSqlSession.commit();
//清理缓存,防止溢出
batchSqlSession.clearCache();
System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
break;// 数据插入完毕,退出循环
} else { result = result + mapper.insertBatch(members.subList(index, batchLastIndex));
batchSqlSession.commit();
//清理缓存,防止溢出
batchSqlSession.clearCache();
System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
index = batchLastIndex;// 设置下一批下标
batchLastIndex = index +(batchCount-1);
}
System.out.println("=============>result=["+result+"] begin=["+index+"] end=["+batchLastIndex+"]");
}
batchSqlSession.commit();
} catch(Exception e) {
e.printStackTrace();
}
finally {
batchSqlSession.close();
}
return true; }

9.test类:

package com.xxx.test.service;

/**
* @desc
* @class BatchInsertTest
* @author create author by deer
* @date 2017年11月28日上午10:01:43
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringBootTest
public class BatchInsertTest { @Autowired
private IotBasRunType222ServiceImpl iotBasRunType222ServiceImpl; @Test
public void test() { try {
iotBasRunType222ServiceImpl.insertBatch(getListDatas());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } private List<IotBasRunType222> getListDatas(){
List<IotBasRunType222> list = new ArrayList<>();
IotBasRunType222 otype = null;
for(int i=1;i<=35;i++) {
otype = new IotBasRunType222();
otype.setRunType(i);
otype.setName("名称"+i);
otype.setNameEn("nameEn"+i);
list.add(otype);
}
return list; }
}

10:参考网址

http://blog.csdn.net/wlwlwlwl015/article/details/50246717
https://teakki.com/p/57df75551201d4c1629b82d5
http://www.cnblogs.com/xcch/articles/2042298.html
http://www.cnblogs.com/admol/articles/4248159.html

springboot-mybatis 批量insert的更多相关文章

  1. Mybatis批量insert 返回主键值和foreach标签详解

    Mybatis批量insert 返回主键 Mybatis从3.3.1版本开始,支持批量插入后返回主键ID.首先对于支持自增主键的数据库使用useGenerateKeys和keyProperty,对于不 ...

  2. Mybatis批量insert报错的解决办法【the right syntax to use near '' at line...】

    Java中使用Mybatis批量插入数据时Mapper.xml中的sql如下: <insert id="batchSave"> into t_emp(emp_name, ...

  3. 第四章 mybatis批量insert

    批量插入sql语句: INSERT INTO table (field1,field2,field3) VALUES ('a',"b","c"), ('a',& ...

  4. Springboot+Mybatis批量导入多条数据

    在Mapper.xml最下面填写 <!-- 批量插入生成的兑换码 --> <insert id ="insertCodeBatch" parameterType= ...

  5. oracle数据库,mybatis批量insert,缺失values字段

    报错:### Error updating database.  Cause: java.sql.SQLException: ORA-00926: 缺失 VALUES 关键字### The error ...

  6. Mybatis 批量insert

    @Override public int insertHouseTypeScene(int htid, String name, String icon,int sort, List<House ...

  7. mybatis 批量insert,update报错 The error occurred while setting parameters

    数据脚本执行正常,但是报错,搜索关键信息 The error occurred while setting parameters ,发现了解决帖子: http://blog.csdn.net/jing ...

  8. oracle+mybatis 使用动态Sql在要insert的字段不确定的情况下实现批量insert

    最近做项目遇到一个挺操蛋的问题,由于业务的关系,DB的数据表无法确定,在使用过程中字段可能会增加,这样在insert时给我造成了很大的困扰. 先来看一下最终我是怎么实现的: <insert id ...

  9. MyBatis :Insert (返回主键、批量插入)

    一.前言    数据库操作怎能少了INSERT操作呢?下面记录MyBatis关于INSERT操作的笔记,以便日后查阅. 二.insert元素 属性详解   其属性如下: parameterType , ...

随机推荐

  1. Druid连接池

    Druid 连接池简介 Druid首先是一个数据库连接池.Druid是目前最好的数据库连接池,在功能.性能.扩展性方面,都超过其他数据库连接池,包括DBCP.C3P0.BoneCP.Proxool.J ...

  2. IIS配置發佈網站常見問題及設置

    解决方法: 修改.NET Framework 版本为相应版本即可,我以前用的是2.0换成4.0的时候出现这个错误. 我的win7系统, 1.打开IIs点击IIS根节点 2.看右边的“操作”->点 ...

  3. win10 uwp 通知列表

    经常看到小伙伴问,问已经绑定列表,在进行修改时,不会通知界面添加或删除.这时问题就在,一般使用的列表不会在添加时通知界面,因为他们没有通知. 本文:知道什么是通知的列表,如何去写一个通知列表 在 C# ...

  4. 张高兴的 Windows 10 IoT 开发笔记:三轴数字罗盘 HMC5883L

    注意,数据不包含校验,准确的来说我不知道怎么校验,但方向看起来差不多是对的... GitHub:https://github.com/ZhangGaoxing/windows-iot-demo/tre ...

  5. SimpleDateFormat时间格式化存在线程安全问题

    想必大家对SimpleDateFormat并不陌生.SimpleDateFormat 是 Java 中一个非常常用的类,该类用来对日期字符串进行解析和格式化输出,但如果使用不小心会导致非常微妙和难以调 ...

  6. 本地idea调试spark2.x程序

    1.构建使用idea 构建maven 项目 选择org.scala-tools.archetypes:scala-archetype-simple,然后一直点next,maven最好选中本地配置国内源 ...

  7. WebService调用(基于KSOAP2)

    public static boolean getData(String param) { //WebService服务器地址 String SERVICE_URL = "http://22 ...

  8. 【20171025早】alert(1) to win 练习

    本人黑绝楼,自称老黑,男,25岁,曾经在BAT工作过两年,但是一直都是底层人员,整天做重复性工作,甚敢无趣,曾和工作十年之久的同事聊天,发现对方回首过往,生活是寡淡如水,只有机械性工作.旋即老黑毅然决 ...

  9. Msys2配置总结

    一.MSYS2的MirrorList配置 1.修改msys2安装目录下的/etc/pacman.d文件夹里面的3个mirrorlist.*文件 [mirrorlist.mingw32] #中国科学技术 ...

  10. getSystemService详解

     android的后台运行在很多service,它们在系统启动时被SystemServer开启,支持系统的正常工作,比如MountService监听是否有SD卡安装及移除,ClipboardServi ...