每次发送过来的数据,会包含多个传感器的值,每个传感器的数据都要存到数据库,如果每次都调用dao去保存,那性能比较低,应该进行优化,要用到mybatis的批量操作
通常大家都会使用mybatis的 <foreach>标签去执行批量的insert操作,这种做法是有问题的,foreach标签中在做字符串的拼接的时候,对于字符串的最大长度是有限制的,如果你的数据特别多,这时拼接会报错,一般的培训机构或网上的教程都不会指明这一点。应该采用另外的办法,就是mybatis的batch操作。
网上的例子
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Transactional(rollbackFor = Exception.class)
@Override
public void batchTest() {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
List<Country> countries = mapper.selectAll();
for (int i = 0; i < countries.size(); i++) {
Country country = countries.get(i);
country.setCountryname(country.getCountryname() + "Test");
mapper.updateByPrimaryKey(country);
//每 50 条提交一次
if((i + 1) % 50 == 0){
sqlSession.flushStatements();
}
}
sqlSession.flushStatements();
}
自己的流程:
1)注入工厂类
//批量插入
@Autowired
private SqlSessionFactory sqlSessionFactory;
2)根据工厂类得到批量操作的session:指定这个参数ExecutorType.BATCH
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
3)执行你的 dao的sava操作
deviceGatherDao.save(deviceGather);//。。。很多的save
4)执行提交
sqlSession.flushStatements();