【问题标题】:List of Java Object from Database with Slowness issues数据库中存在缓慢问题的 Java 对象列表
【发布时间】:2018-03-30 14:11:32
【问题描述】:

我正在编写一个 java 代码,一切都很好,但我开始在我的 GUI 中尝试一些缓慢的问题。这是我的代码:

//some code..
//get articles from database
//in this case listOfArticles  contains 1000 Objects
listOfArticles = service.getArticles();

//loop through listOfArticles to get another data from my database
for (Article article: listOfArticles) {

//each list may conatins 100 to 200 Objects
//in this case I'm going to the database 1000 times and this maybe the cause of the Slowness 
listOfInfo = service.getInfoById(article.getId());

//...some code
}

在 GUI 中我等待 20 秒到 30 秒才能得到结果,你有什么建议可以优化响应时间或避免进入我循环中的数据库。

提前致谢

【问题讨论】:

  • 是否有可能将大量文章分解成块并仅以按需方式获取有关它们的信息?
  • 图像等不应在对象中。使用 JPA 时需要小心得到什么:较重的字段,如列表。

标签: java oop arraylist


【解决方案1】:

要减少数据库访问次数,请使用所有 Article id 填充一个 List,然后创建一个具有以下签名的方法(适应您的需要):

public List<Info> getInfoByIds(List<Long> articleIdList)

该方法应该以在单个数据库访问中获取所有 Info 对象的查询结束(JPQL 中的示例):

select i from Info i where i.ID in :idList

再一次,在不了解您的代码的情况下,我无法更具体。

【讨论】:

    【解决方案2】:

    好吧,我的回答看起来很模糊,但我会给你两个建议:

    1. 使用some pagination(例如一次显示50个项目)或使用无限滚动。
    2. 使用一种方法一次返回多篇文章。 (你可以看看 Bernat 给出的例子)

    【讨论】:

      猜你喜欢
      • 2014-05-02
      • 2021-07-12
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多