Multiple query conditions on Android using ORMLITE

I want to make a simple request with several conditions

I use OrmLite to display an entity object.

Now I want to find the object in my table.

Suppose I have a Person object that displays the PERSON table, what I want to do is initialize the object with some parameters and do a search.

Assume the function searchPerson(Person oPerson)

If I pass an OPerson object like this

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

Can I write a request to achieve this? 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 make several requests this way

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

but I also want to check if a value exists

+4
source share
2

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

@ArghArgh , AND. , AND , - . - :

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

where.and(int), AND .

+8

, QueryBuilder. -

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

List<Person> list = PersontDao.query(preparedQuery);
+1

Source: https://habr.com/ru/post/1540975/


All Articles