JAVA 批量插入数据

tech2023-10-25  110

提供一份批量插入数据代码给网友用用

package co.dc.saas.stockdata.util; import co.dc.saas.commons.base.BaseDao; import co.dc.saas.commons.base.BasePo; import co.dc.saas.commons.utils.PoDefaultUitls; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * 批量保存数据 * * @author Jerry * */ @Slf4j @Component public class BatchSaveUtils { // 事务提交数量 private static final int COMMIT_NUM = 20000; @Autowired private SqlSessionFactory sqlSessionFactory; public <M extends BaseDao<T>, T extends BasePo> void batchSave(List<T> list, Class<M> clazz) { long startTime = System.currentTimeMillis(); /* 关闭自动提交事务 */ SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false); // 通过新的session获取mapper M m = session.getMapper(clazz); try { for (int i = 0; i < list.size(); i++) { T t = list.get(i); // 设置ID等字段 PoDefaultUitls.saveDefault(t); m.insert(t); if (i > 0 && i % COMMIT_NUM == 0) { session.commit(); session.clearCache(); } } session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); log.info("批量保存数据耗時:" + (System.currentTimeMillis() - startTime) + " ms"); } } public <M extends BaseDao<T>, T extends BasePo> void batchUpdate(List<T> list, Class<M> clazz) { long startTime = System.currentTimeMillis(); /* 关闭自动提交事务 */ SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false); // 通过新的session获取mapper M m = session.getMapper(clazz); try { for (int i = 0; i < list.size(); i++) { m.updateByPrimaryKey(list.get(i)); if (i > 0 && i % COMMIT_NUM == 0) { session.commit(); session.clearCache(); } } session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); log.info("批量更新数据耗時:" + (System.currentTimeMillis() - startTime) + " ms"); } } }

 

最新回复(0)