Briareos386
Briareos386

Reputation: 1957

GreenDAO toMany Relation - Target Entities Order

I have a toMany relation in my schema ("A human has 1..N cats"). If I query a entity for its toMany-target entities I use the following code:

List<Cat> cats = human.getCatList();

Is the returned list guaranteed to be ordered? If yes, dependant on which property?

Additional Information (Generation Code):

In my schema (generator) the entities are created as follows:

Entity human = schema.addEntity("human");
human.addIdProperty().autoincrement();

Entity cat = schema.addEntity("cat");
cat.addIdProperty().autoincrement();
pb = cat.addLongProperty("humanId");
pb.notNull();
pb.indexAsc(null, false);

human.addToMany(cat, pb.getProperty());

I therefore thought the order is (implicitly) defined by the created index, but a look at CatDao.java showed the index is created without a defined order:

"CREATE INDEX " + constraint + "IDX_CAT_HUMAN_ID ON CAT (HUMAN_ID);"

Changing the pb.indexAsc to pb.indexDesc does change the index name, but not the index order of the column (see: SQLite Syntax: indexed-column).

So - is this wanted behavior? How can I define the order of target entities?

Upvotes: 1

Views: 731

Answers (1)

Briareos386
Briareos386

Reputation: 1957

Is the returned list guaranteed to be ordered? If yes, dependant on which property?

Short answer yes with an if; long answer no with a but: The order of items is implicitly not defined but can be explicitly set at the toMany relationship.

human.addToMany(cat, [...]).orderAsc([...]);

will yield the generation of an ORDER BY statement in the created Cat.java for the Human entity (see Cat#_queryHuman_CatList).

I therefore thought the order is (implicitely) defined by the created index, but a look at CatDao.java showed the index is created without a defined order.

This seems to be wanted behavior because, as the SQLite Docs state: Each column name can be followed by one of the "ASC" or "DESC" keywords to indicate sort order. The sort order may or may not be ignored depending on the database file format [...] - given that GreenDAO supports older Android versions (and therefore older SQLite versions, see SO question/answer here) not appending the sort order on an index makes sense.

Upvotes: 1

Related Questions