我是Google应用引擎的新手。我用JPA编写了一个简单的webapps来存储和检索数据。我的程序成功地将数据插入数据库(JPA)(数据显示在谷歌应用程序引擎的数据存储页面中),但在检索时我收到“java.lang.NullPointerException”错误。
我的节目
package com.alokpanda;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class SaveAndView extends HttpServlet {
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String address = request.getParameter("address");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("transactions-optional");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
User user = new User();
user.setName(name);
user.setAddress(address);
em.persist(user);
em.getTransaction().commit();
em.close();
emf.close();
response.setContentType("plain/text");
PrintWriter out = response.getWriter();
EntityManagerFactory emf2 = null;
EntityManager em2 = null;
Query query = null;
List<User> list = null;
try {
emf2 = Persistence.createEntityManagerFactory("transactions-optional");
} catch (Exception e) {
out.print(e);
}
try {
em2 = emf2.createEntityManager();
} catch (Exception e) {
out.print("em problem :"+e);
}
try {
query = em2.createQuery("SELECT u FROM User u", User.class);
list = query.getResultList();
if(list != null) {
out.print(list);
} else {
out.print("null");
}
} catch (Exception e) {
out.print(e+" : ");
out.print(query+" : ");
out.print(list+" : ");
out.print(em);
}
}
}
节目输出
java.lang.NullPointerException : SELECT u FROM User u : null : org.datanucleus.api.jpa.JPAEntityManager@161b59f3