Objectify Google App Engine

Currently I am working on a google app engine application.
Instead of using the Dataservice functions I wanted something with an orm feel.
So I stumbled across Objectify google app engine.

On your pom file just add

        <!-- Objectify for google app engine -->
        <dependency>
            <groupId>com.googlecode.objectify</groupId>
            <artifactId>objectify</artifactId>
            <version>4.0b1</version>
        </dependency>

And let’s make some crud operations.

First Let’s create an Entity


package com.gkatcode.objectifycrud;

import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;


@Entity
public class Title {

    @Id
    Long id;
    @Index
    private String name;

    public Title() {}

    public Title(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

In order to be able to perform queries and filter values such as the name you need to add the Index annotation.

Then you have to register the entity to the datastore at the intialization of the application

ObjectifyService.register(Title.class);

And your are ready to go

package com.gkatcode.objectifycrud;

import com.googlecode.objectify.ObjectifyService;
//static import of the function
import static com.googlecode.objectify.ObjectifyService.ofy;

public class ObjectifyCrud() {

/**
Put a title
*/
public static void saveTitle(Title title ) {
ofy().save().entity(title).now();
}

/**
query a title, returns Title object
*/
public static Title getTitle(String name) {
return ofy().load().type(Title.class).filter("name",name).first().get();
}

/**
Delete title
*/
public static void deleteTitle(Title title) {
ofy().delete().type(Title.class).id(title.getId()).now();
}

/**
Get Titles
*/
public static List getTitles() {
return ofy().load().type(Title.class).list();
}

}
Advertisement

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.