在MyBatis中可以通过在xml中配置<foreach>标签来进行批量操作。比如如下代码:

但有时候我们想要对其控制的更加细粒度(比如设置多少条语句操作后commit),可以通过java编码的方式来进行处理。
MyBatis中最重要的三个接口分别是SqlSessionFactory,SqlSession,Executor。MyBatis在操作数据的时候离不开SqlSession接口实例类的作用。在实际开发中一般默认使用DefaultSqlSession类。
下面上源代码:

方法barchExecute有两个入参,第一个是 Statement,相当于mybatis配置文件中namespace与节点id结合的全称,如下图中statement则为com.palic.sales.eOperate.calendarmeet.mapper.CalendarMeetMappper.mergeBatchCalMeet
第二个参数为你想要批量插入的List对象集合。


首先通过SqlSessionFactory的openSession(ExecutorType execType, boolean autoCommit)方法获得一个SqlSession实例对象。其中第一个参数是一个枚举类,该枚举类用以区分Executor的种类。查看源码可以得知主要有三种种类:

分别对应的意思如下:
ExecutorType.SIMPLE: 这个执行器类型不做特殊的事情。它为每个语句的执行创建一个新的预处理语句。
ExecutorType.REUSE: 这个执行器类型会复用预处理语句。
ExecutorType.BATCH: 这个执行器会批量执行所有更新语句,如果 SELECT 在它们中间执行还会标定它们是 必须的,来保证一个简单并易于理解的行为。
在此处我们选择ExecutorType.BATCH类型。第二个参数则是选择是否自动提交,在此选择false。
通过调用sqlSession的insert方法来实现新增功能。下面可以进入查看源代码。


这里可以看到最终调用的是Executor的update方法完成更新功能。
网友评论