首页 新闻 会员 周边

mybatis mysql 批量插入数据

0
悬赏园豆:10 [待解决问题]

最近在网上学的jsoup爬数据,爬了大概几万条城市地区的数据准备通过mybatis插入的mysql里,九个字段除了ID,其它都是varchar类型,区划代码是十二位数字暂时也是用的varchar;

想过三种插入方式

1:service层循环调用dao层插入数据,一条一条来

2:拼接sql类似 insert into citytable (province,...) select ... union all select ... union all
在后台先拼接几百条然后插入

3:xml里用foreach循环插入

请问有其它方法可以快速插入数据吗?求学中,路过的大神请多指教

空城灬无旧人的主页 空城灬无旧人 | 初学一级 | 园豆:115
提问于:2019-07-11 11:50
< >
分享
所有回答(3)
0

以现代的计算机运行速度,我觉得你的代码不管写得有多么烂,几万条数据问问题等回答的时间里面都应该插入完成了。
如果你真的这么好学的话,那很简单,把你说的三种方法都写出来,测试一下。
然后你会发现,代码中有很多不合理的地方,优化后,再测试一下,结果又有不同。
如果你还能好好总结,查询一下相关的资料,为什么这儿慢,原因是......
那么这么一件事已经够你做个半个来月。

爱编程的大叔 | 园豆:30839 (高人七级) | 2019-07-11 12:05

首先...谢谢你的回答,你说的这些我会注意的;其次...我并不是单纯的等答案复制代码去测试之类的,既然想到了那肯定也写过测过,发出来是想听听别人的看法见解,吸收学习,闭门造车总归不太好的,对吧?

支持(0) 反对(0) 空城灬无旧人 | 园豆:115 (初学一级) | 2019-07-11 12:39
0

给你提供一个的思路:以批量添加用户为例
SSM框架下:
Spring的配置文件中需要添加一个用于执行批量操作的sqlSession

代码:
<!-- 配置一个可以执行批量的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- name:SqlSessionTemplate类构造方法的形参名 value:形参值 ref:引用工厂 -->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>

测试类:
@RunWith(SpringJUnit4ClassRunner.class)//指定用哪个单元测试运行
@ContextConfiguration(locations={"classpath:applicationContext.xml"})//指定Spring配置文件的位置
public class Test {

@Autowired
User user;

@Autowired
SqlSession sqlSession;

@Test
public void test(){
    int i;
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    for(i = 0;i<1000;i++){
        String uid = UUID.randomUUID().toString().substring(0,5)+i;//用户名随机生成
        mapper.insertSelective(new User(null,uid, uid+"@atguigu.com"));//批量添加用户
    }
    System.out.println("批量添加完成");
}

}

如果你只用Mybatis,那么Spring中配置的可以执行批量的sqlSession你应该会转换吧?转换思路:
它就是用了org.mybatis.spring.SqlSessionTemplate这个类的两个参数的构造器,
一个参数写你工厂类对外提供的工厂,一个参数写BATCH,通过这个 构造器可以new 一个Sqlsession实例,之后的代码就就跟上述的测试类中的方法代码一样了

nreg | 园豆:206 (菜鸟二级) | 2019-07-15 13:35
0

我能想到的是用InsertProvider,
Insert into xxx (xx,xxx,xxx,)
for(xx,xx,xx){
values(xx,xxx,xxx)
}

n490808114 | 园豆:215 (菜鸟二级) | 2019-09-25 11:29
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册