mybtias oracle 批量插入

使用mybatis操作数据库是现代开发的一种趋势,因为mybatis具有更好的灵活性和可维护性。在mybatis的操作中,批量数据插入是一个非常常见的需求。

在mybatis中实现批量数据插入的方法有很多种,但是最常用的还是使用oracle的批量插入语句。oracle支持使用insert all into语句来实现批量数据插入,可以一次性将多条记录插入到数据库中,在高并发的场景下可以很好地提高系统的性能表现。

下面是使用mybatis实现oracle批量插入的代码:

public void batchInsert(Listlist) { SqlSession sqlSession = sqlSessionFactory.openSession(); Connection connection = sqlSession.getConnection(); PreparedStatement statement = connection.prepareStatement("insert into table_name (column1,column2,column3) values(?,?,?)"); // 设置不自动提交,因为此处需要进行多次插入 connection.setAutoCommit(false); try { int i = 0; for (Bean bean: list) { statement.setObject(1, bean.getColumn1()); statement.setObject(2, bean.getColumn2()); statement.setObject(3, bean.getColumn3()); statement.addBatch(); // 每1000条数据插入一次 if (i % 1000 == 0 && i != 0) { statement.executeBatch(); connection.commit(); statement.clearBatch(); } i++; } statement.executeBatch(); connection.commit(); } catch (SQLException e) { connection.rollback(); e.printStackTrace(); } finally { try { statement.close(); sqlSession.close(); } catch (SQLException e) { e.printStackTrace(); } } }