循环中频繁查询数据库优化
业务中出现在循环中频繁查询数据库对比数据,频繁连接数据库耗费资源。
利用SQL语句进行批量查询 存为一个List,如通过简单的where条件查询全部 select * from table where <?>;
如果是通过SQL查询出来的List作为条件判断去查询,可以通过stream.map在List中获取查询中需要的List;
List<ObjectDTO>.stream().map(ObjectDTO::getId).collect(Collectors.toList());
上面的stream就能返回一个id的List, 然后就可以通过List去查询,避免循环中查询数据库。
通过多个id,即List去查询一个List, 而每个id 可能对应多个ObjectDTO时,
为了使id与多个DTO一一对应,可以使用Map接收查询结果,即Map<Long id, List>;
具体实现就是利用stream中的分组函数,如下
list<ObjectDTO>.stream().collect(Collectors.groupingByConcurrent(ObjectDTO::getBorrowId));
数据库SQL进行条件查询时候,where是传入字符串时加一个非空判断,
最初直接这样判断<if test="returningKey != null"> 如果returningKey为String <if test="returningKey != null && returningKey !="" ">
