Skip to content

Instantly share code, notes, and snippets.

@narendrans
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save narendrans/9100594 to your computer and use it in GitHub Desktop.

Select an option

Save narendrans/9100594 to your computer and use it in GitHub Desktop.
Google App Engine Java DataStore example
package info.narendran;
import java.io.IOException;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
@SuppressWarnings("serial")
public class DatastoreSample extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
PersistenceManagerFactory PMF = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
PersistenceManager pm = PMF.getPersistenceManager();
if (req.getParameter("method").equals("put")) {
Product product = new Product("1001", "jeans", 12.34);
Product product1 = new Product("1002", "pants", 64.98);
Key key = KeyFactory.createKey(Product.class.getSimpleName(),
"1001");
product.setKey(key);
Key key1 = KeyFactory.createKey(Product.class.getSimpleName(),
"1002");
product1.setKey(key1);
try {
pm.makePersistent(product);
pm.makePersistent(product1);
} finally {
pm.close();
}
} else if (req.getParameter("method").equals("get")) {
Product e = pm.getObjectById(Product.class, req.getParameter("id"));
resp.getWriter().println(
"Product: " + e.getName() + ", Price: " + e.getPrice());
}
}
}
package info.narendran;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
@PersistenceCapable
public class Product {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String name;
@Persistent
private String id;
@Persistent
private double price;
public Product(String id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment