【问题标题】:Collection update optimization集合更新优化
【发布时间】:2020-07-23 10:34:23
【问题描述】:

例如,我们在 DB 中收集存储对象(例如简化为 String):

Collection<String> existed = someRepository.findElements(); //returns "A", "B", "B", "C"

我们有一个必须替换旧数据的新集合:

Collection<String> received = Arrays.asList("B", "C", "C" ,"D");

第一个想法是从数据库中删除所有以前的数据并从received 集合中保存所有数据,例如:

someRepository.removeAll(existed);
someRepository.saveAll(received);

但是如果有很多共同元素,就会导致应用程序和数据库之间的数据传输过剩。

另一方面,我们可以找到要删除、添加的元素,但它需要大量的equals 方法调用,并且检查内存中的所有项目会比较慢,恕我直言,这不好。

最相似的预期结果是:

  • “A”,第二个“B”将在 toRemove 集合中(我们调用 removeAll
  • 一个“C”、“D”将在 toAdd 集合中(我们调用 saveAll
  • 普通的“B”和“C”不会被触及

那么您有什么解决方案可以更优化地解决此类情况吗? 谢谢。

【问题讨论】:

  • 为什么不使用地图或(更好的)LinkedHashSet 来表示“已存在”?每个键只能出现一次,因此您不必搜索重复项。
  • @Calaf 当然,但我们也需要从 db 中删除重复项。对于休眠这些对象是不同的

标签: java hibernate collections spring-data-jpa


【解决方案1】:

已从 Apache Commons 找到实用程序:

Collection intersection = CollectionUtils.intersection(existed, received); //intersection between 2 collections

Collection toRemove = CollectionUtils.disjunction(existed, intersection); //getting disjunction between existed and intersection
Collection toAdd = CollectionUtils.disjunction(received, intersection); //getting disjunction between received and intersection

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多