当真理还正在穿鞋的时候,谎言就能走遍半个世界。------马克吐温
之前写过一个,最近感觉不好用
然后写了一个更优雅的
|---------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 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; }
|
使用方式同样很简单
两个例子:
调用方传入对应的DAO
和条件参数以及limit
随机获取的条数即可