这里写目录标题

为何要写这篇文章

今天优化了下别人的代码,区区500条数据的查询接口查询到5s时间。具体原因是当我们查询数据库的时候,需要注意一些不良习惯。

内容

// 例如
// 从数据库取出主表
List<Student> students = getStudentList();
for (Student student: students) {
// 从这里开始开始查询
Level level = studentMapper.getLevelByStudentId(student.getId());
// 然后就无限在for循环种查询对应的熟悉进行封装
}

当在for循环里进行查询的时候,每一次就连接数据库,这样一来效率自然也会降低。
举个例子,一百个苹果,你是打算分一次拿完,还是一个一个来回去拿?

解决方案

Set<Long> ids = students.stream().map(t->t.getId()).
collect(Collectors.toSet());
Map<Long, Level> maps = getLevelByStudentIds(ids );
for (Student student: students) {
student.setLevelName(maps.get(student.getLevelId()))
}

总结

这样封装数据的方法有很多,for循环语句进行查询时,会造成不必要的时间浪费。有时查询的时候也可以用in语句查询,当然也要尽量走索引,提升一下性能,虽然这微不足道。

更多推荐