Filter Query Results With Objectify


Objectify is a Java data access API specifically designed for the Google App Engine datastore.
It is an easy way to use Google Datastore.

In this blog we are going to filter a single attribute for multiple values.

Now lets start with creating an entity.
The first step is to define your entity class. Here is an example of employee.

public class Employee
{
    @Id
    public Long Id;
    String fname;
    String lname;

    private Employee() {}

    public Employee(String fname, String lname)
    {
        this.fname = fname;
        this.lname = lname;
    }
}


Now before applying any datastore operation, we must register all our classes with the objectifyservice.

ObjectifyService.register(Employee.class);

Basic operations in objectify are: Get, Put and Delete.

We can obtain an Objectify interface from the ObjectifyService:

 Objectify ofy = ObjectifyService.begin();
1.Employee emp = new Employee("Scott", "Tiger");  //putting data
2.Employee emp1 = new Employee("John", "Smith");
3.Employee emp2 = new Employee("Marry", "Jhons");
4.ofy.put(emp,emp1,emp2);

5.Employee empfetch = ofy.get(Employee.class, emp.id);  //getting data
6.Employee empfetched1 = ofy.get(Employee.class, emp1.id);
7.Employee empfetched2 = ofy.get(Employee.class, emp2.id);

8.ofy.delete(emp);  //deleting data

Now our final step is querying
Every time you load() an Employee, it will fetch the entire list.
Large numbers of data will bloat the entity and impact performance.
Lets start with

Objectify ofy = ObjectifyService.begin();
Query q = ofy.query(Emplyee.class).filter("FirstName", john);

This statement will show all the employee name started with john.

With Objectify, you have the option to use the in operator in a query

IN operator performs multiple queries, one for each item in the
specified list. The results are merged, in the order of the items in the list.
For instance,

List Name = new ArrayList();
Name.add("john");
Name.add("scott");
Query q = ofy.query(Employee.class).filter("FirstName in", Name);
About these ads
This entry was posted in Java, Web and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s