Mybatis的批量处理

MyBatis高效处理10,000条批量更新的最佳实践 处理10,000条批量更新时,MyBatis提供了多种解决方案。经过实践验证,ExecutorType.BATCH方式在大多数场景下表现最优。开发者应根据具体业务需求、数据库类型和数据规模选择合适的方案,同时注意事务管理、错误处理和性能监控,才能实现真正高效的批量操作。 阅读详情

1.配置文件

   jdbc.properties,需要注意,需要加allowMultiQueries=true配置

[html]  view plain  copy
  1. #MySql  
  2. jdbc.driverClassName=com.mysql.jdbc.Driver  
  3. jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/mybatis?useUnicode\=true&characterEncoding\=UTF-8&allowMultiQueries\=true  
  4. jdbc.username=root  
  5. jdbc.password=root  
 mybatis-config.xml

[html]  view plain  copy
  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.     <properties resource="jdbc.properties"/>  
  7.     <typeAliases>  
  8.         <package name="com.mybatis.model"/>  
  9.     </typeAliases>  
  10.     <environments default="development">  
  11.         <environment id="development">  
  12.             <transactionManager type="JDBC" />  
  13.             <dataSource type="POOLED">  
  14.                 <property name="driver" value="${jdbc.driverClassName}" />  
  15.                 <property name="url" value="${jdbc.url}" />  
  16.                 <property name="username" value="${jdbc.username}" />  
  17.                 <property name="password" value="${jdbc.password}" />  
  18.             </dataSource>  
  19.         </environment>  
  20.         <environment id="test">  
  21.             <transactionManager type="JDBC" />  
  22.             <dataSource type="POOLED">  
  23.                 <property name="driver" value="${jdbc.driverClassName}" />  
  24.                 <property name="url" value="${jdbc.url}" />  
  25.                 <property name="username" value="${jdbc.username}" />  
  26.                 <property name="password" value="${jdbc.password}" />  
  27.             </dataSource>  
  28.         </environment>  
  29.     </environments>  
  30.     <mappers>  
  31.         <package name="com.mybatis.mappers"/>  
  32.     </mappers>  
  33. </configuration>  
2.接口Mapper:StudentMapper

[java]  view plain  copy
  1. import java.util.List;  
  2. import java.util.Map;  
  3.   
  4. import com.mybatis.model.Student;  
  5.   
  6. public interface StudentMapper {  
  7.     /** 
  8.      * 通过List集合批量插入 
  9.      * @param list 
  10.      * @return 
  11.      */  
  12.     public int batchInsertStudentWithList(List<Student> list);  
  13.     /** 
  14.      * 通过IdList进行Update特定字段为特定值 
  15.      * @param list 
  16.      * @return 
  17.      */  
  18.     public int batchUpdateByIdList(List<Integer> list);  
  19.     /** 
  20.      * 通过Map批量更新 
  21.      * @param map 
  22.      * @return 
  23.      */  
  24.     public int batchUpdateStudentWithMap(Map<String, Object> map);  
  25.     /** 
  26.      * 通过List集合批量更新 
  27.      * @param list 
  28.      * @return 
  29.      */  
  30.     public int batchUpdateStudentWithList(List<Student> list);  
  31.       
  32.     /** 
  33.      * 通过数组进行批量删除 
  34.      * @param array 
  35.      * @return 
  36.      */  
  37.     public int batchDeleteStudentWithArray(int array[]);  
  38.     /** 
  39.      * 能过IdList进行批量删除 
  40.      * @param list 
  41.      * @return 
  42.      */  
  43.     public int batchDeleteStudentWithIdList(List<Integer> list);  
  44.     /** 
  45.      * 通过list删除 
  46.      * @param list 
  47.      * @return 
  48.      */  
  49.     public int batchDeleteStudentWithList(List<Student> list);  
  50.     /** 
  51.      * 通过list中对象进行删除 
  52.      * @param list 
  53.      * @return 
  54.      */  
  55.     public int batchDeleteStudentWithListOnlyId(List<Student> list);  
  56. }  
3.Mapper配置StudentMapper

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper  
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  5. <mapper namespace="com.mybatis.mappers.StudentMapper">  
  6.   
  7.     <!-- 1,size:表示缓存cache中能容纳的最大元素数。默认是1024;   
  8.          2,flushInterval:定义缓存刷新周期,以毫秒计;   
  9.          3,eviction:定义缓存的移除机制;默认是LRU(least recently userd,最近最少使用),还有FIFO(first in   
  10.             first out,先进先出)   
  11.          4,readOnly:默认值是false,假如是true的话,缓存只能读。 -->  
  12.     <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false" />  
  13.   
  14.     <resultMap type="Student" id="StudentResult">  
  15.         <id property="id" column="id" />  
  16.         <result property="name" column="name" />  
  17.     </resultMap>  
  18.   
  19.     <delete id="batchDeleteStudentWithArray" parameterType="java.lang.String">  
  20.         DELETE FROM t_student where id in  
  21.         <foreach item="idItem" collection="array" open="(" separator=","  
  22.             close=")">  
  23.             #{idItem}  
  24.         </foreach>  
  25.     </delete>  
  26.       
  27.     <delete id="batchDeleteStudentWithIdList" parameterType="java.util.List">  
  28.         DELETE FROM t_student where id in  
  29.         <foreach collection="list" item="idItem" index="index" open="("  
  30.             separator="," close=")">  
  31.             #{idItem}  
  32.         </foreach>  
  33.     </delete>  
  34.       
  35.       
  36.     <delete id="batchDeleteStudentWithListOnlyId" parameterType="java.util.List">  
  37.         DELETE FROM t_student where id in  
  38.         <foreach collection="list" index="index" item="item" open="("    
  39.             separator="," close=")">    
  40.             #{item.id}    
  41.         </foreach>    
  42.     </delete>  
  43.       
  44.       
  45.     <!-- 效率低,不推荐 -->  
  46.     <delete id="batchDeleteStudentWithList" parameterType="java.util.List">  
  47.         <foreach collection="list" item="item" index="index" open="" close="" separator=";">  
  48.         DELETE  FROM t_student  
  49.             where id=#{item.id}  
  50.         </foreach>  
  51.     </delete>  
  52.       
  53.     <update id="batchUpdateByIdList" parameterType="java.util.List">  
  54.         UPDATE t_student set name='test' where id in  
  55.         <foreach collection="list" item="idItem" index="index" open="("  
  56.             separator="," close=")">  
  57.             #{idItem}  
  58.         </foreach>  
  59.     </update>  
  60.   
  61.     <update id="batchUpdateStudentWithList" parameterType="java.util.List">  
  62.         <foreach collection="list" item="item" index="index" open="" close="" separator=";">  
  63.         UPDATE t_student  
  64.             <set>  
  65.                 name=#{item.name}  
  66.             </set>  
  67.             where id=#{item.id}  
  68.         </foreach>  
  69.     </update>  
  70.   
  71.     <update id="batchUpdateStudentWithMap" parameterType="java.util.Map">  
  72.         UPDATE t_student SET name = #{name} WHERE id IN  
  73.         <foreach collection="idList" index="index" item="idItem" open="("  
  74.             separator="," close=")">  
  75.             #{idItem}  
  76.         </foreach>  
  77.     </update>  
  78.       
  79.     <insert id="batchInsertStudentWithList" parameterType="java.util.List">  
  80.         INSERT INTO /*+append_values */ t_student (name)  
  81.         VALUES  
  82.         <foreach collection="list" item="item" index="index" separator=",">  
  83.             (#{item.name})  
  84.         </foreach>  
  85.     </insert>  
  86. </mapper>   
 4.SqlSessionFactoryUtil
[java]  view plain  copy
  1. package com.mybatis.util;  
  2.   
  3. import java.io.InputStream;  
  4.   
  5. import org.apache.ibatis.io.Resources;  
  6. import org.apache.ibatis.session.SqlSession;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  9.   
  10. public class SqlSessionFactoryUtil {  
  11.   
  12.     private static SqlSessionFactory sqlSessionFactory;  
  13.       
  14.     public static SqlSessionFactory getSqlSessionFactory(){  
  15.         if(sqlSessionFactory==null){  
  16.             InputStream inputStream=null;  
  17.             try{  
  18.                 inputStream=Resources.getResourceAsStream("mybatis-config.xml");  
  19.                 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);  
  20.             }catch(Exception e){  
  21.                 e.printStackTrace();  
  22.             }  
  23.         }  
  24.         return sqlSessionFactory;  
  25.     }  
  26.       
  27.     public static SqlSession openSession(){  
  28.         return getSqlSessionFactory().openSession();  
  29.     }  
  30. }  
5.Model:Student
[java]  view plain  copy
  1. package com.mybatis.model;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Student implements Serializable {  
  6.   
  7.     private Integer id;  
  8.     private String name;  
  9.     private byte[] pic;// blob  
  10.     private String remark;// clob  
  11.     public Student() {  
  12.         super();  
  13.         // TODO Auto-generated constructor stub  
  14.     }  
  15.   
  16.     public Student(Integer id, String name) {  
  17.         super();  
  18.         this.id = id;  
  19.         this.name = name;  
  20.     }  
  21.   
  22.     public Student(String namee) {  
  23.         super();  
  24.         this.name = name;  
  25.     }  
  26.   
  27.     public Integer getId() {  
  28.         return id;  
  29.     }  
  30.   
  31.     public void setId(Integer id) {  
  32.         this.id = id;  
  33.     }  
  34.   
  35.     public String getName() {  
  36.         return name;  
  37.     }  
  38.   
  39.     public void setName(String name) {  
  40.         this.name = name;  
  41.     }  
  42.   
  43.     public byte[] getPic() {  
  44.         return pic;  
  45.     }  
  46.   
  47.     public void setPic(byte[] pic) {  
  48.         this.pic = pic;  
  49.     }  
  50.   
  51.     public String getRemark() {  
  52.         return remark;  
  53.     }  
  54.   
  55.     public void setRemark(String remark) {  
  56.         this.remark = remark;  
  57.     }  
  58.   
  59.     @Override  
  60.     public String toString() {  
  61.         return "Student [id=" + id + ", name=" + name + ", remark=" + remark + "]";  
  62.     }  
  63.   
  64. }  
6.测试类

[java]  view plain  copy
  1. package com.mybatis.service;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.apache.ibatis.session.SqlSession;  
  9. import org.apache.log4j.Logger;  
  10. import org.junit.After;  
  11. import org.junit.Before;  
  12. import org.junit.Test;  
  13.   
  14. import com.mybatis.mappers.StudentMapper;  
  15. import com.mybatis.model.Student;  
  16. import com.mybatis.util.SqlSessionFactoryUtil;  
  17.   
  18. public class StudentBatchTest {  
  19.   
  20.     private static Logger logger=Logger.getLogger(Student.class);  
  21.     private SqlSession sqlSession=null;  
  22.     private StudentMapper studentMapper=null;  
  23.       
  24.     /** 
  25.      * 测试方法前调用 
  26.      * @throws Exception 
  27.      */  
  28.     @Before  
  29.     public void setUp() throws Exception {  
  30.         sqlSession=SqlSessionFactoryUtil.openSession();  
  31.         studentMapper=sqlSession.getMapper(StudentMapper.class);  
  32.     }  
  33.   
  34.     /** 
  35.      * 测试方法后调用 
  36.      * @throws Exception 
  37.      */  
  38.     @After  
  39.     public void tearDown() throws Exception {  
  40.         sqlSession.close();  
  41.     }  
  42.       
  43.     //通过list进行批量插入  
  44.     @Test  
  45.     public void batchInsertStudentWithList(){  
  46.           List<Student> list= new ArrayList<Student>();  
  47.             for(int i = 2;i < 10;i++){  
  48.                 Student student = new Student();  
  49.                 student.setName("test" + i);  
  50.                 list.add(student);  
  51.             }  
  52.             int n=studentMapper.batchInsertStudentWithList(list);  
  53.             System.out.println("成功插入"+n+"条记录");  
  54.             sqlSession.commit();  
  55.     }  
  56.     //分页批量插入  
  57.     @Test  
  58.     public void batchInsertStudentPage(){  
  59.         List<Student> list= new ArrayList<Student>();  
  60.         for(int i = 0;i < 2000;i++){  
  61.             Student student = new Student();  
  62.             student.setName("test" + i);  
  63.             list.add(student);  
  64.         }  
  65.         try {  
  66.             save(list);  
  67.         } catch (Exception e) {  
  68.             e.printStackTrace();  
  69.         }  
  70.     }  
  71.       
  72.     private void save(List<Student> uidCodeList) throws Exception {  
  73.         SqlSession batchSqlSession = null;  
  74.         try {  
  75.             batchSqlSession =SqlSessionFactoryUtil.openSession();//获取批量方式的sqlsession          
  76.             int batchCount = 1000;//每批commit的个数  
  77.             int batchLastIndex = batchCount - 1;//每批最后一个的下标  
  78.             for(int index = 0; index < uidCodeList.size()-1;){  
  79.                 if(batchLastIndex > uidCodeList.size()-1){  
  80.                     batchLastIndex = uidCodeList.size() - 1;  
  81.                     batchSqlSession.insert("com.mybatis.mappers.StudentMapper.batchInsertStudentWithList", uidCodeList.subList(index, batchLastIndex+1));  
  82.                     batchSqlSession.commit();  
  83.                     System.out.println("index:"+index+"     batchLastIndex:"+batchLastIndex);  
  84.                     break;//数据插入完毕,退出循环  
  85.                       
  86.                 }else{  
  87.                     batchSqlSession.insert("com.mybatis.mappers.StudentMapper.batchInsertStudentWithList", uidCodeList.subList(index, batchLastIndex+1));                                   batchSqlSession.commit();  
  88.                     System.out.println("index:"+index+"     batchLastIndex:"+batchLastIndex);  
  89.                     index = batchLastIndex + 1;//设置下一批下标  
  90.                     batchLastIndex = index + (batchCount - 1);                        
  91.                 }                 
  92.             }                         
  93.         }finally{  
  94.             batchSqlSession.close();  
  95.         }         
  96.     }  
  97.     //通过IdList批量更新  
  98.     @Test  
  99.     public void batchUpdateByIdList() {  
  100.         logger.info("通过IdList批量更新");  
  101.         List<Integer> list = new ArrayList<Integer>();  
  102.         list.add(5);  
  103.         list.add(6);  
  104.         int n = studentMapper.batchUpdateByIdList(list);  
  105.         System.out.println("成功更新" + n + "条记录");  
  106.         sqlSession.commit();  
  107.     }  
  108.   
  109.     //通过map进行批量更新  
  110.     @Test  
  111.     public void batchUpdateStudentWithMap() {  
  112.         List<Integer> ls = new ArrayList<Integer>();  
  113.         for (int i = 5; i < 7; i++) {  
  114.             ls.add(i);  
  115.         }  
  116.         Map<String, Object> map = new HashMap<String, Object>();  
  117.         map.put("idList", ls);  
  118.         map.put("name", "小群11");  
  119.         int n = studentMapper.batchUpdateStudentWithMap(map);  
  120.         System.out.println("成功更新" + n + "条记录");  
  121.         sqlSession.commit();  
  122.     }  
  123.     //通过list批量更新  
  124.     @Test  
  125.     public void batchUpdateStudentWithList() {  
  126.         logger.info("更新学生(带条件)");  
  127.         List<Student> list = new ArrayList<Student>();  
  128.         list.add(new Student(6, "张三aa"));  
  129.         list.add(new Student(6, "李四aa"));  
  130.         int n = studentMapper.batchUpdateStudentWithList(list);  
  131.         System.out.println("成功更新" + n + "条记录");  
  132.         sqlSession.commit();  
  133.     }  
  134.       
  135.     //通过Array进行批量删除  
  136.     @Test  
  137.     public void batchDeleteStudentWithArray() {  
  138.         logger.info("删除学生,通过Array");  
  139.         int array[] = new int[] { 3, 4 };  
  140.         studentMapper.batchDeleteStudentWithArray(array);  
  141.         sqlSession.commit();  
  142.     }  
  143.     @Test  
  144.     public void batchDeleteStudentWithIdList() {  
  145.         logger.info("通过IdList批量更新");  
  146.         List<Integer> list = new ArrayList<Integer>();  
  147.         list.add(9);  
  148.         list.add(10);  
  149.         int n = studentMapper.batchDeleteStudentWithIdList(list);  
  150.         System.out.println("成功删除" + n + "条记录");  
  151.         sqlSession.commit();  
  152.     }  
  153.     @Test  
  154.     public void batchDeleteStudentWithList() {  
  155.         logger.info("通过IdList批量更新");  
  156.         List<Student> list = new ArrayList<Student>();  
  157.         list.add(new Student(12, null));  
  158.         list.add(new Student(13, null));  
  159.         int n = studentMapper.batchDeleteStudentWithList(list);  
  160.         System.out.println("成功删除" + n + "条记录");  
  161.         sqlSession.commit();  
  162.     }  
  163.       
  164.     @Test  
  165.     public void batchDeleteStudentWithListOnlyId() {  
  166.         logger.info("通过IdList批量更新");  
  167.         List<Student> list = new ArrayList<Student>();  
  168.         list.add(new Student(14, null));  
  169.         list.add(new Student(15, null));  
  170.         int n = studentMapper.batchDeleteStudentWithListOnlyId(list);  
  171.         System.out.println("成功删除" + n + "条记录");  
  172.         sqlSession.commit();  
  173.     }  
  174.       
  175. }  
联想Y9000P安装Ubuntu20.04记录 联想Y9000P 2022安装Ubuntu20.04问题记录 阅读详情

相关推荐

unity | 动画模块之滚动选项框

动画模块之滚动选项框

菌菌兹的博客 2075

Mybatis 批量操作8种实现总结

Mybatis 批量操作8种实现总结超全带实例

程序员小强的博客 2万+

实战|验证码突破思路

漏洞成因:由于逻辑设计缺陷,可绕过验证,比如直接删除COOKIE或验证码参数可绕过、当验证不通过清空session时,验证码参数值为空时绕过等。测试方法:抓包,删除验证码字段,查看是否可以成功发送抓包,正常流程下,记录验证码后的数据包,替换目标包中内容,直接发送,查看是否可以直接绕过验证码案例:Step1.输入正确账户信息和错误验证码,登录时抓包Step2.删除COOKIEStep3.客户端登陆成功。

weixin_46239998的博客 8106

Mybatis批处理

Mybatis批处理 第一种 单条SQL循环操作 1.Mapper.xml ``` <insert id="insert" parameterType="com.example.mybatisbatch.entity.OrderDetail"> insert into order_detail values (#{order.id},#{order.name},#{order.phone},#{order.expressNo},#{order.productName},#{ord

MostSnails的博客 7901

SAP-PP 返工订单成本归集优化:从物料结算到成本中心的配置与增强实践

本文深入探讨SAP-PP模块中返工订单成本归集的优化方案,重点解析从物料结算到成本中心的配置与增强实践。通过结算参数文件配置、分配结构调整及增强开发实战,解决返工费用误计入物料成本的问题,确保财务核算精准性。文章还提供测试验证方案与常见报错处理技巧,助力企业实现成本数据清晰流向分析。

weixin_29260291的博客 366

【STM32】STM32F407实现简单的Modbus协议

1.ModBus协议简介 MODBUS协议是一种串行通信协议,由Modicon公司(施耐德公司前身)发表,由于其公开发表且无版权要求,易于部署和维护,在工业界广泛应用。MODBUS采用主从通信(Master/Slave),MODBUS有三种报文格式:ASCII、RTU、TCP,本文主要讨论RTU。 如下图所示,串行通信上的MODBUS协议主要由地址,功能码,数据,CRC校验四部分数据帧构成。主机和从机的串行通信设备要求一致,参数要求一致,即假设使用串口,主从机波特率,奇偶校验...

BadBoyHolly的博客 8188

Mybatis的批处理操作详解

Mybatis批处理操作 文章目录Mybatis批处理操作一、Foreach方式批量插入批量更新批量删除二、Batch方式三、preparedStatement方式总结 一、Foreach方式 批量插入 插入方式一: 注:(oracle不支持,mysql支持,有返回插入行数) <insert id="insertByBatch" parameterType="java.util.List"> INSERT INTO WBM_ERT_DED_RST_T ( <i

weixin_41979002的博客 5804

Xilinx同步FIFO IP核的两种读模式对比:Standard vs FWFT(附Vivado仿真代码)

本文深入解析Xilinx同步FIFO IP核的两种读模式——Standard与FWFT,通过时序仿真和Vivado代码示例对比其性能差异。Standard模式适合严格流水线设计,而FWFT模式在低延迟场景表现更优。文章包含详细的testbench搭建指南和性能实测数据,帮助FPGA工程师优化数据流设计。

table的专栏 348

MyBatis批处理

批处理即批量处理。如果需要往数据库中插入大量数据时,再使用单条插入即插入一次调一次insert语句就会很浪费资源。所以针对于批量数据新增、删除、修改、查找的操作,mybatis提供了批处理方案 批量插入 除了可以向SQL语句中传入单一的数据类型,还可以传输一个list集合,利用foreach标签就可以循环遍历集合中的内容实现批处理,例如: Mapper XML: <insert id="batchInsert" parameterType="java.util.List"> INSERT

Do_GH的博客 3255

ADAS方案设计-CAN网络管理与休眠唤醒机制

文章摘要:本文介绍了车载控制系统的五种工作模式及其转换条件,包括睡眠模式、准备睡眠模式、就绪睡眠模式、正常工作模式和重复消息状态。系统唤醒条件包括接收到网络管理报文或电源ON档信号,休眠条件则需满足电源OFF档、功能完成等多重要求。针对下挂节点的网络管理报文发送规则,详细说明了不同状态下的报文发送策略,特别是在哨兵模式、OTA模式等特殊场景下的处理方式。系统在满足休眠条件后会立即停止发送下挂节点网络管理报文,确保电源管理的有效性。

xiandang8023的博客 325

Unity3D实现视频和模型融合效果

在Unity中,视频和3D模型融合通常涉及到将视频表面内嵌到3D场景中。视频不影响模型的展示, 这可以通过使用Shader和Texture来实现。大家好,我是心疼你的一切,不定时更新Unity开发技巧,觉得有用记得一键三连哦。下面就让我们进入正文吧!提示:以下是本篇文章正文内容,下面案例可供参考本次介绍的就是视频和模型融合的实现,以后有其他的需要添加的会继续添加不定时更新Unity开发技巧,觉得有用记得一键三连哦。么么哒。

心疼你的一切博客 5357

mybatis的批处理

需要注意的是,在使用MyBatis的批处理功能时,应该根据具体情况选择合适的方式,并合理控制批处理的大小,以避免占用过多资源或影响数据库性能。通过合理使用MyBatis的批处理功能,可以提高数据库操作的效率,减少与数据库的交互次数,从而提升系统的整体性能。在执行多个不同的SQL语句时,可以将多个SQL语句的执行转换为一次执行,减少与数据库的交互次数,提高效率。在执行多次相同的SQL语句时,可以将多次执行转换为一次执行,减少与数据库的交互次数,提高效率。

B__B_B的博客 965

Android功耗系列专题分析之四:待机概率性功耗高的失效分析

本文分析了Android设备待机功耗异常高的问题。通过日志发现系统休眠失败,原因是PowerManagerService.Display唤醒锁未被释放。进一步排查发现,指纹解锁功能在灭屏时未正确释放屏幕锁定,导致DisplayReady状态异常。解决方案是将指纹功能的背光控制与DisplayReady状态控制分离,使用两个变量独立管理。经验表明,快速定位问题比解决问题更重要,修改原生流程时需谨慎评估风险。

452

mybatis之批量处理

批量处理即对多条数据进行sql操作,如批量更新,插入,新增。 之前采取过很low的方式,就是在dao层进行循环,对每条数据进行操作。这样效果可以实现,但是频繁连接数据库,性能,效率上非常不好。mybatis支持参数为list的操作,这样连接数据库就一次,把循环的语句写入到sql语句中,这样效率会高很多。 如何引入mybatis这里不做描述。 先看service层方法如何写 service ...

青蛙的博客 3263

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

MyBatis的批量处理与批量操作

1.背景介绍 MyBatis是一款非常受欢迎的Java数据访问框架,它可以简化数据库操作,提高开发效率。在实际应用中,我们经常需要对数据库中的多条记录进行批量处理和批量操作。在这篇文章中,我们将深入探讨MyBatis的批量处理与批量操作,揭示其核心概念、算法原理、最佳实践以及实际应用场景。 1. 背景介绍 在数据库操作中,我们经常需要对大量数据进行处理,例如插入、更新、删除等。如果使用单条S...

AI天才研究院 895

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

mybatis 批量处理数据

新增批量处理数据 insert 允许 values(),(),() <insert id="insertSelective" parameterType="java.lang.String" > insert into T_Alarm_Group_Rel_Param (AlarmGroupID,AlarmID) values <foreach collect...

HEshenghuxi的博客 784

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【Mybatis的批量处理】

Mybatis的批量处理操作 1. 一般批量处理 链接: mybatis批量更新数据三种方法效率对比 2. 使用BatchExecutor进行批量处理 若方法一中的方法无法满足业务需要时,可使用Mybatis的批量处理器进行批量处理。 通过依赖注入的方式声明sqlSessionTemplate工具; @Autowired private SqlSessionTemplate sqlSessionTemplate; 先通过sqlSessionTemplate获取工厂实例,然后再获取指定执行器的sqlS

m0_46459413的博客 1404

Mybatis批量处理

可以通过全局配置文件指定默认的Executor开启批量处理模式: <setting name="defaultExecutorType" value="BATCH"/> 如果在全局配置文件中指定的话BATCH模式的话,所有的其他不需要批量处理的sql,都默认使用了Batch模式,所以正常情况下在应该在获取sqlSession的时候指定使用Batch类型的Executo...

ajhvele180232的博客 325

Mybatis的批量操作,在Spring中使用Mybatis的批量处理

//使用批量插入的方法向数据库中插入100条记录 @Test public void testbatchsave2() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession session = sqlSessionFactory.openSession(Exe...

qq_43257103的博客 1310

mybatis做批量插入时,当数据为null时的处理

当mybatis做批量插入时,插入的字段可能没值,此时不做处理的话,mybatis会报异常,执行失败 根据mybatis的官网介绍,此时需要添加对应的jdbcType类型映射,以处理null值 mybatis和数据库字段的对应关系 Mybatis JdbcType Oracle MySql JdbcType ARRAY JdbcType BIGINT BIGINT JdbcType BINARY ...

一步一个脚印_binding 6953

Mybatis批量事务处理

/** * 批量提交数据 * @param sqlSessionFactory * @param mybatisSQLId SQL语句在Mapper XML文件中的ID * @param commitCountEveryTime 每次提交的记录数 * @param list 要提交的数据列表 ...

dianzhouyu4467的博客 634

mybatis批量处理的使用和核心源码解析

mybatis批量处理 一. 今天给大家分享关于mybatis的批量处理使用和源码分析,大家都知道mybatis是对JDBC的封装,其底层使用的还是JDBC, 所以我们先一起来了解JDBC 的批处理代码如下 public static void main(String[] args) { try { Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/

qq_32699791的博客 1081

mybatis 批量处理

SqlSessionFactory在创建SqlSession实例时候可以设置ExecutorType,这个枚举类型定义了 3 个 值: ExecutorType.SIMPLE: 这个执行器类型不做特殊的事情。它为每个语句的执行创建一个新的预处理语句。 ExecutorType.REUSE: 这个执行器类型会复用预处理语句。 ExecutorType.BATCH: 这个执行器会批量执...

siyuan_zhu的专栏 269

mybatis批量插入、批量更新操作及null问题处理

mybatis批量插入、批量更新操作及null问题处理 mybatis批量插入、批量更新常规写法,及升级写法 null value in column “xxx” violates not-null constraint mybatis批量操作报错问题处理 批量插入 常规写法 <insert id="insertUser" parameterType="com.test.UserEnti...

嫒de洫天使 1万+

MyBatis处理批量删除

MyBatis处理批量删除

weixin_52385232的博客 566

Mybatis中批量处理

批量查询 <select id="listStudent" resultType="Student"> SELECT <include refid="Base_Column_List"/> FROM student WHERE id IN <foreach collection="list" open"(" close=")" separator="," i...

熙熙小学姐 271
上一篇: Dom4j实现xml简单的增删改查功能
下一篇: mybatis的一级缓存和二级缓存
Java_funds
博客等级 码龄9年 6粉丝 22原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值