简体   繁体   English

如何使用SQL数据库中的列表有效加载对象

[英]How to efficiently load objects with lists from sql-databases

Supposed I have the following class: 假设我有以下课程:

class Example {
  List<ObjectA> objectsOfA;
  List<ObjectB> objectsOfB;
  List<ObjectC> objectsOfC;    
  ....
}

I would usually have these tables: 我通常会有这些表:

  • Example (Id, other-attributes) Example (Id,其他属性)
  • ObjectA (some attributes, ExampleId) ObjectA (某些属性,ExampleId)
  • ObjectB (some attributes, ExampleId) ObjectB (某些属性,ExampleId)
  • ObjectC (some attributes, ExampleId) ObjectC (某些属性,ExampleId)

If I want to restore an Example -object, I imagine I have two options: 如果我想还原Example -object,我想我有两个选择:

  1. join every table together, resulting in a lot of entries and organizing it in hashmaps to reassemble the objects 将每个表连接在一起,产生大量条目并将其组织在哈希图中以重新组装对象
  2. loading every Example and for every example doing single requests for the lists of ObjectA , ObjectB , ObjectC . 加载每个Example并为每个示例执行对ObjectAObjectBObjectC列表的单个请求。

If the number of Example -entries is low, option2 might be the best. 如果Example -entries的数量很少,则option2可能是最好的。 But for every single entry in Example , I need to do x more requests where x is the number of tables in my class. 但是对于Example每个单个条目,我需要执行x个以上的请求,其中x是类中表的数量。

Otherwise, having everything in a single join requires me to reorganize all the data by myself - creating hashmaps, iterating through data and stuff, which is usually a lot of work in code. 否则,将所有内容都放在一个联接中就需要我自己重新组织所有数据-创建哈希表,遍历数据和内容,这通常是代码中的大量工作。

I also get the possibility of lazy loading with option 2. 我还可以通过选项2进行延迟加载。

Do I have other choices? 我还有其他选择吗? Did I miss something? 我错过了什么? (Of course I know about ORMs, but I decided to not use them on Android) (我当然知道ORM,但是我决定在Android上不使用它们)

If I understood correctly, your question is, which of these ways is better to load data from a main table and related tables: 如果我正确理解,您的问题是,从主表和相关表中加载数据哪种方法更好:

  1. Load a JOIN of the main table and related tables 加载主表和相关表的JOIN
  2. Load the data of the main table and related tables separately and join them in Java 分别加载主表和相关表的数据,并用Java将它们联接
  3. Something else 还有别的

Unless you are extremely constrained for bandwidth, I'd say option 1 is simple and I would go with that. 除非您对带宽有极大的限制,否则我会说选项1很简单,我会同意的。 It's easier to let the DB do the joining and in Java just map the records to objects. 让数据库进行连接更容易,而在Java中,只需将记录映射到对象即可。

If saving bandwidth with the database is important, then option 2 is better, because every piece of data will be fetched only once without duplication, as the result of a JOIN in option is essentially denormalized data. 如果节省数据库的带宽很重要,那么选项2会更好,因为每条数据将只获取一次而不会重复,因为选项中的JOIN结果实际上是非规范化数据。

In any case, I recommend to follow Occam's razor : the simplest solution is often the best. 无论如何,我建议您使用Occam的剃刀 :最简单的解决方案通常是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM