Multiple Query Condition in Android using ORMLITE
Asked Answered
H

2

5

i want to make a simple query, with multiple conditions

I use OrmLite to map entity object.

Now I want to search for an object into my table.

Supposing i have a Person entity that maps PERSON table, what I want to do is to initialize an object with some parameters and search it.

Suppose a function searchPerson(Person oPerson)

If i pass an object OPerson like this

Id = null
Name = John
Age = null
Sex = male

Is possible to write a query to reach that goal? Something like this pseudo-code

pers = (from p in db.Table<Person>() 
                     where (if OPerson.Id !=null) p.Id==OPerson.Id}
                     AND {(if OPerson.Name !=null) p.Name.Contains(OPerson.Name)}
                     AND {(if condition) where-contion}
                     select p).ToList();

I know that i can do multiple query in this way

list=PersonDao.queryBuilder().where().eq("name",OPerson.name)
    .and().eq("sex",OPerson.sex").query();

but I want also to check if the value exists

Henninger answered 17/5, 2014 at 15:59 Comment(0)
R
9

where (if OPerson.Id !=null) p.Id==OPerson.Id}

@ArghArgh is close but doesn't have the ANDs right. The problem is that the AND statements are conditional on whether there were any previous statements. I'd do something like:

QueryBuilder<Person, Integer> queryBuilder = dao.queryBuilder();
Where<Person, Integer> where = queryBuilder.where();
int condCount = 0;
if (oPerson.id != null) {
    where.eq("id", oPerson.id);
    condCount++;
}
if (oPerson.name != null) {
    where.like("name", "%" + oPerson.name + "%");
    condCount++;
}
...
// if we've added any conditions then and them all together
if (condCount > 0) {
    where.and(condCount);
}
// do the query
List<Persion> personList = queryBuilder.query();

This makes use of the where.and(int) method which takes a number of clauses on the stack and puts them together with ANDs between.

Requiem answered 18/5, 2014 at 17:59 Comment(0)
C
1

I think that you must use the QueryBuilder. Try something like this

QueryBuilder<Person, Integer> queryBuilder = PersonDao.queryBuilder();
// get the WHERE object to build our query
Where<Person, String> where = queryBuilder.where();
if(oPerson.Name!=null)
    where.like("Name", "%"+oPerson.Name+"%");
// and
where.and();
if(Person.Sex!=null)
    where.like("Sex", "%"+oPerson.sex+"%");

PreparedQuery<Person> preparedQuery = queryBuilder.prepare();

Than you can call it in this way

List<Person> list = PersontDao.query(preparedQuery);
Cuffs answered 18/5, 2014 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.