51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

mybatis-plus随机查询工具类(二)

当真理还正在穿鞋的时候,谎言就能走遍半个世界。------马克吐温

之前写过一个,最近感觉不好用

然后写了一个更优雅的

|---------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | hljs java /** * 随机查询 * * @param mapper 持久层DAO * @param limit 随机条数 * @return java.util.List<T> * @author <achao1441470436@gmail.com> * @since 2021/8/10 15:30 */ public static <T> List<T> getAny(BaseMapper<T> mapper, T condition, Integer limit) { LambdaQueryWrapper<T> wrapper = Wrappers.lambdaQuery(condition); Integer total = mapper.selectCount(wrapper); if (limit == null || limit <= 0 || total == 0) { return Collections.emptyList(); } List<T> list = Optional.of(limit).filter(l -> l > total).map(l -> mapper.selectList(wrapper)).orElseGet(() -> mapper.selectList(wrapper.last("LIMIT " + new SecureRandom().nextInt(total - (limit - 1)) + "," + limit))); Collections.shuffle(list); return list; } |

使用方式同样很简单

image-20210810224358310

两个例子:

image-20210810224423293

调用方传入对应的DAO和条件参数以及limit随机获取的条数即可

赞(0)
未经允许不得转载:工具盒子 » mybatis-plus随机查询工具类(二)