Saturday, 14 May 2011

Google App Engine + JDO (Java Data Objects)

First step is to do the JDO setup. This requires creating the jdoconfig file in the application's war/WEB-INF/classes/META-INF/ directory.


<?xml version="1.0" encoding="utf-8"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig">
    <persistence-manager-factory name="transactions-optional">
        <property name="javax.jdo.PersistenceManagerFactoryClass"
            value="org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManagerFactory"/>
        <property name="javax.jdo.option.ConnectionURL" value="appengine"/>
        <property name="javax.jdo.option.NontransactionalRead" value="true"/>
        <property name="javax.jdo.option.NontransactionalWrite" value="true"/>
        <property name="javax.jdo.option.RetainValues" value="true"/>
        <property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
    </persistence-manager-factory>
</jdoconfig>

Next step is to create the persistence manager factory in the data access layer part of your application.


import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

public final class PMF {

 private static final PersistenceManagerFactory pmfInstance = JDOHelper
   .getPersistenceManagerFactory("transactions-optional");

 private PMF() {
 }

 public static PersistenceManagerFactory get() {
  return pmfInstance;
 }
 public static PersistenceManager getPersistenceManager(Object obj) {
  return JDOHelper.getPersistenceManager(obj);
 }
}

Now using persistence manager you can access the data by executing JDO query like this:


import java.util.List;
import javax.jdo.PersistenceManager;
import com.gifito.server.dao.entity.EmployeeMaster;

public class EmployeeDaoImpl implements EmployeeDao {

 @SuppressWarnings("unchecked")
 public static List getListOfEmployees() {
  PersistenceManager pm = PMF.get().getPersistenceManager();
  String query = "select from " + EmployeeMaster.class.getName();
  List employees = (List) pm.newQuery(
    query).execute();
  return employees;
 }
}

The last step is to call the close method on persistence manager instance.

No comments:

Post a Comment