Google App Engine and JPA

Using JPA on the Google AppEngine is straight forward. For some reason the documentation on the official Google App Engine side is not very easy to read therefore a little example here.

Create a new web project “de.vogella.gae.persistence.jpa”. Change the generated Servlet to “PersistsServlet” and adjust the “web.xml”. Create the following two classes. The first will be your tiny data model and the other will buffer the creation of the EntityManagerFactory which can be time consuming.

package de.vogella.gae.persistence.jpa.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Todo {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long todoId;
	private String summary;

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}
}
package de.vogella.gae.persistence.jpa.model;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EMFService {
	private static final EntityManagerFactory emfInstance = Persistence
			.createEntityManagerFactory("transactions-optional");

	private EMFService() {
	}

	public static EntityManagerFactory get() {
		return emfInstance;
	}
}

Below “src/META-INF” create the following file which will configure JPA for the Google App Engine.

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

    <persistence-unit name="transactions-optional">
        <provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider</provider>
        <properties>
            <property name="datanucleus.NontransactionalRead" value="true"/>
            <property name="datanucleus.NontransactionalWrite" value="true"/>
            <property name="datanucleus.ConnectionURL" value="appengine"/>
        </properties>
    </persistence-unit>

</persistence>

Now change the code of your servlet to the following. This servlet will create a new Todo every time it is called and displays the today number of Todos to the user.

package de.vogella.gae.persistence.jpa;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.vogella.gae.persistence.jpa.model.EMFService;
import de.vogella.gae.persistence.jpa.model.Todo;

@SuppressWarnings("serial")
public class PersistsServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		Todo todo = new Todo();

		todo.setSummary("This is my todo");

		EntityManager em = EMFService.get().createEntityManager();
		List<Todo> todos = null;
		try {
			em.persist(todo);
			Query q = em.createQuery("select t from Todo t");
			todos = new ArrayList(q.getResultList());
		} finally {
			em.close();
		}

		resp.setContentType("text/plain");
		if (todos != null) {
			resp.getWriter().println(
					"Hello, JPA. We have " + todos.size()
							+ " number of entries.");
		} else {
			resp.getWriter().println("Should not happen");
		}
	}
}

Thats it. Run your example and access your servlet. See that the number of entries is increasing every time you hit the servlet.

That’s it! Deploy the application to the Google App Engine to be able to chat with it. Of course where is more to JPA and Google AppEngine but you can use my tutorials to learn more about them.

JPA Tutorial
Google App Engine Tutorial

You can also follow me on Twitter.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Web and tagged , , . Bookmark the permalink.

2 Responses to Google App Engine and JPA

  1. kartoch says:

    Good post. Is there a reason you use GenerationType.IDENTITY instead of GenerationType.AUTO ? The other id generation modes are not supported ?

  2. Lars Vogel says:

    @kartoch: No particular reason. I haven’t tried GenerationType.AUTO as GenerationType.IDENTITY worked for me.

Comments are closed.