【问题标题】:How to fetch thousands of database records efficiently using JPA 2 and QueryDSL?如何使用 JPA 2 和 QueryDSL 有效地获取数千条数据库记录?
【发布时间】:2017-06-16 08:26:49
【问题描述】:

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

public List<EntryEntity> getEntries() {

QEntryEntity qEntryEntity = QEntryEntity.entryEntity;

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

【问题讨论】:

  • 是什么让您无法使用纯 SQL 执行此操作?
  • 如果 orderBy(qEntryEntity.name.asc()) 排序是由java完成的,从本地机器数据库获取数据大约需要3分钟。
  • 我的前辈有一个特殊要求,要求我在 QueryDSL 和 JPA 中执行此操作,而不使用任何本机查询。
  • 好吧,那么一直在花费什么时间呢?您是否分析了您的查询?
  • name 列上放置一个索引怎么样?

标签: java spring-data spring-data-jpa querydsl


【解决方案1】:

您可能在 NAME 列上缺少索引:

CREATE INDEX solve_all_problems ON entry_entity (name);

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多