I've got a list of primary keys and I need these elements from my greendao database.
The most trivial method would be to query each object idividually and inserting it into a list:
public List<MyObject> getMyObjectByIds(List<String> ids) {
List<MyObject> result = new ArrayList<MyObject>();
for (String id : ids) {
QueryBuilder<MyObject> queryBuilder = myObjectDao.queryBuilder();
MyObject myObject = queryBuilder.where(MyObjectDao.Properties.Id.eq(id)).unique();
result.add(myObject);
}
return result;
}
However this seem quite ineffective since it would have to do ids.size() queries. A single query with multiple OR statements would be better. However, since the whereOr() and or() methods only except 2 or more parameters you'd have to make quite a few IF ELSE statements to catch lists with 0, 1 or 2 ids:
public List<MyObject> getMyObjectByIds(List<String> ids) {
QueryBuilder<MyObject> queryBuilder = myObjectDao.queryBuilder();
if (ids.size() == 0) {
List<MyObject> result = new ArrayList<MyObject>();
return result;
} else if (ids.size() == 1) {
return queryBuilder.where(MyObjectDao.Properties.Id.eq(ids.get(0))).list();
} else if (ids.size() == 2) {
queryBuilder.whereOr(MyObjectDao.Properties.Id.eq(ids.get(0)), MyObjectDao.Properties.Id.eq(ids.get(1)));
return queryBuilder.list();
} else if (ids.size() >= 3) {
queryBuilder.whereOr(MyObjectDao.Properties.Id.eq(ids.get(0)), MyObjectDao.Properties.Id.eq(ids.get(1)), getWhereConditionsEqIdRefFromThirdElementOn(ids));
return queryBuilder.list();
}
}
private WhereCondition[] getWhereConditionsEqIdFromThirdElementOn(List<String> ids) {
WhereCondition[] whereConditions = new WhereCondition[ids.size() - 1];
for (int i = 2; i < ids.size(); ++i) {
whereConditions[i] = MyObjectDao.Properties.Id.eq(ids.get(i));
}
return whereConditions;
}
Honestly, this might be faster but it still seems quite ugly to me. Is there another way? Or do I have to make a raw query?
Aucun commentaire:
Enregistrer un commentaire