1、使用 ORDER BY RAND()
(MySQL)
对于 MySQL 数据库,你可以使用 ORDER BY RAND()
来随机排序结果。例如,如果你想要随机获取 5 条记录,可以这样做:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import com.king.YourEntity;
import com.king.KingEntityService ;
public class KingTest {
@Autowired
private KingEntityService kingEntityService ;
public void getRandomRecords() {
QueryWrapper<YourEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.orderBy(true, true, "RAND()");
Page<KingEntity> page = new Page<>(1, 5);
Page<KingEntity> result = yourEntityService.page(page, queryWrapper);
result.getRecords().forEach(System.out::println);
}
}
2、使用 DBMS 特定的函数
(如 SQL Server 的 NEWID()
)
queryWrapper.orderBy(true, true, "NEWID()");
3、使用 LIMIT
和 ORDER BY
(PostgreSQL, MySQL, SQLite 等)
对于支持 LIMIT
子句的数据库(如 PostgreSQL, MySQL, SQLite),你可以结合使用 ORDER BY RAND()
(MySQL)或相应的随机函数来实现:
queryWrapper.last("ORDER BY RAND() LIMIT 5");
或者使用原生 SQL:
yourEntityService.list(new QueryWrapper<YourEntity>().last("ORDER BY RAND() LIMIT 5"));
4、使用 MyBatis Plus 的 IPage
和 PageHelper
(如果你使用的是较旧的版本)
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
public void getRandomRecordsWithPageHelper() {
PageHelper.startPage(1, 5);
List<YourEntity> list = yourEntityService.list();
Collections.shuffle(list);
List<YourEntity> randomList = list.subList(0, Math.min(5, list.size()));
}