简体   繁体   中英

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)
  • ObjectA (some attributes, ExampleId)
  • ObjectB (some attributes, ExampleId)
  • ObjectC (some attributes, ExampleId)

If I want to restore an Example -object, I imagine I have two options:

  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 .

If the number of Example -entries is low, option2 might be the best. But for every single entry in Example , I need to do x more requests where x is the number of tables in my class.

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.

Do I have other choices? Did I miss something? (Of course I know about ORMs, but I decided to not use them on 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
  2. Load the data of the main table and related tables separately and join them in Java
  3. Something else

Unless you are extremely constrained for bandwidth, I'd say option 1 is simple and I would go with that. It's easier to let the DB do the joining and in Java just map the records to objects.

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.

In any case, I recommend to follow Occam's razor : the simplest solution is often the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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