如何使用 JPA 2 和 QueryDSL 高效地获取数以千计的数据库记录?

How to fetch thousands of database records efficiently using JPA 2 and QueryDSL?

目前我有一个实现可以在 10-12 秒内获取 10,000 条记录。可以改进此查询的性能,如何改进?以下是我基于 QueryDSL 和 JPA 2 的代码片段。

public List<EntryEntity> getEntries() {

QEntryEntity qEntryEntity = QEntryEntity.entryEntity;

return queryfactory.selectFrom(qEntryEntity).orderBy(qEntryEntity.name.asc()).fetch();
}

您可能缺少该 NAME 列的索引:

CREATE INDEX solve_all_problems ON entry_entity (name);

这很有效,因为索引预先排序了所有数据,因为它是一个有序的数据结构,所以当您 运行 查询像您的查询时,数据库不再需要做任何排序工作现在正在 运行ning。 Use-the-index-luke has a nice explanation on this topic.

旁注:添加索引时要小心。虽然它们大大加快了读取操作,但每个索引都会减慢对该列的写入操作。每个指标都是一个权衡。