1. 程式人生 > >springboot-mybatis 批量insert

springboot-mybatis 批量insert

att ssr time 映射 兼容 tlist return isp element

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>
View Code

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);
    }
}
View Code

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>
View Code

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
View Code

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。。。
}
View Code

6.java mapper:

技術分享圖片
package com.xxx.mapper;


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

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>
View Code

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;

}
View Code

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;
        
    }
}
View Code

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