Mybatis批量插入数据的三种方式分享
下文笔者讲述Mybatis插入数据的方法分享,如下所示
for循环insert
long start = System.currentTimeMillis(); for(int i = 0 ;i < 100000; i++) { User user = new User(); user.setId("id" + i); user.setName("name" + i); user.setPassword("password" + i); userMapper.insert(user); } long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); <insert id="insert"> INSERT INTO t_user (id, name, password) VALUES(#{id}, #{name}, #{password}) </insert>
Mybatis batch模式
SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);//跟上述sql区别 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { User user = new User(); user.setId("id" + i); user.setName("name" + i); user.setPassword("password" + i); userMapper.insert(user); } sqlSession.commit(); long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); <insert id="insert"> INSERT INTO t_user (id, name, password) VALUES(#{id}, #{name}, #{password}) </insert>
批量foreach插入
long start = System.currentTimeMillis(); list<User> userList = new ArrayList<>(); for (int i = 0; i < 100000; i++) { User user = new User(); user.setId("id" + i); user.setName("name" + i); user.setPassword("password" + i); userList .add(user); } userMapper.insertBatch(userList); long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); <insert id="insertBatch" parameterType="java.util.List"> INSERT INTO t_user (id, name, password) VALUES <foreach collection ="userList" item="user" separator =","> (#{user.id}, #{user.name}, #{user.password}) </foreach > </insert>
当批量增加数据量较多时 建议采用batch模式 foreach一次性插入数据量建议10-100条 for循环是最不建议的方式 需要频繁的建立关闭数据库连接,比较耗时
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。