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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.