Today we will go little deeper in understanding the advance functionality of db4o and its querying mechanism. QBE is easy but We need more sophisticated mechanisms of querying in actual android applications, and that’s Native Queries.
Native queries provide us absolute power of conditional querying. We can query an object by any of its fields and using all conditional operators and we can combine our quries using logical operators AND, OR, NOT. Lets start with an example. Lets say we have a Contact class
Class Contact{
Public String name;
Public String number;
Public int age;
Public boolean member;
}
Querying based on conditions is very easy in db4o than in relational databases. We have a predicate function in which we can write any condition which should be true. Lets see :
Find a contact where number= 1234
ObjectSet result = db.query(new Predicate() {
public boolean match(Contact conObj) {
return (conObj.number.equal(“1234”));
}
});
find a contact where age=20
ObjectSet result = db.query(new Predicate() {
public boolean match(Contact conObj) {
return (conObj.age==20);
}
});
to get all objects of type Contact
ObjectSet result = db.query(new Predicate() {
public boolean match(Contact conObj) {
return true;
}
});
Note that we are using db.query instead of db.QBE. db.query return us one or more matching objects in result which Contact type object set. We can iterate result to get objetcs. We can write any expression in match function which should be true when querying objects.
To retrieve found objects, check the result returned by db.query
if(result.hasNext()) // if result is not empty
Contact obj= result.Next();
and if you want to return all objects returned by query
ArrayList list=new ArrayList();
while(result.hasNext()){
list.add(result.Next());
}
that’s it about native queries. There are some other interesting things like indexing for fast querying and dealing with objects containing other objects. You are encouraged to read about them in db4o reference document and tutorial.