GAE using Objectify

Objectify是GAE Java的一個lightware IoC framework
透過Objectify可以達到與Spring相似的IoC功能
下面是操作Objectify的一些過程:

Step1: Download Objectify library

本文下載的是objectify 3.1版本的

Step2: Create Entity class

Objectify是針對Entity Object來進行資料的存取動作,因此需要先建立Car的Entity類別

package com.mitac.objectify;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Car {
    @Id 
    String idx; // Can be Long, long, or String
    
    String name;
    
    public Car(String idx, String name) {
    this.idx = idx;
    this.name = name;
    }
}
  
Step3: Create service middleware

建立static class的middleware來作為呼叫Objectify的中介

package com.mitac.objectify;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
public class OfyService {
    static {
        factory().register(Car.class);
        //... etc
    }
    public static Objectify ofy() {
        return ObjectifyService.begin();
    }
    public static ObjectifyFactory factory() {
        return ObjectifyService.factory();
    }
}

Step4: Using middleware to put data

package com.mitac.objectify;
import static com.mitac.objectify.OfyService.ofy;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class GaeObjectifyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {

ofy().put(new Car("audi", "audi a3"));
Car car = ofy().get(Car.class, "audi");

resp.setContentType("text/plain");
resp.getWriter().println("Hello, world ==> " + car.name );
}
}

Other: Query example

查詢的方式跟Low Level API差不多,範例如下:

Query<Car> query = ofy().query(Car.class);
query.filter("name = ", "audi a3").order("name");
List<Car> cars = query.list();
Iterator iter = cars.iterator();
while(iter.hasNext()) {
    Car c = (Car) iter.next();
    out.println("Hello, world ==> " + c.name );
}

參考文獻: