Tuesday 8 January 2013

Using Database for Object (db4o) in android part-2

In previous post we discussed db4o benefits over relational databases and saw how we can setup and use db4o in android applications.

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<Contact> result = db.query(new Predicate<Contact>() {
public boolean match(Contact conObj) {
return (conObj.number.equal("1234"));
}
});

find a contact where age=20


ObjectSet<Contact> result = db.query(new Predicate<Contact>() {
public boolean match(Contact conObj) {
return (conObj.age==20);
}
});

to get all objects of type Contact

ObjectSet<Contact> result = db.query(new Predicate<Contact>() {
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<Contact> list=new ArrayList<Contact>();

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.

No comments:

Post a Comment