Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Query Condition in Android using ORMLITE

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

like image 913
second Avatar asked May 17 '14 15:05

second


2 Answers

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.

like image 62
Gray Avatar answered Oct 18 '22 12:10

Gray


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);
like image 1
ArghArgh Avatar answered Oct 18 '22 14:10

ArghArgh