我正在尝试检索一个简单的 JSON 列表,将此 JSON 数组转换为 Eclipselink 对象并将它们放入 postgres。尽管我不断从 EntityManager 获取空指针,但我已经迷失了方向。
我从测试网络服务调用我的控制器:
@WebServlet(name = "Test", urlPatterns = {"/Test"})
public class Test extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// HERE I CALL CUSTOM METHODS
AppController appConn = new AppController();
appConn.updateAppList();
} finally {
out.close();
}
}
在控制器中,我试图保留这些转换后的对象:
public class AppController {
@PersistenceUnit(unitName="UserPU")
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();
public AppController() {
}
public void updateAppList() {
try {
URLController urlConn = new URLController(Config.allAppsURL);
JsonElement jelement = new JsonParser().parse(urlConn.toString());
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("applist");
JsonArray jarray = jobject.getAsJsonArray("apps");
ArrayList<SteamApp> apps = new ArrayList<App>(){};
for(int i = 0; i < jarray.size(); i++) {
JsonObject jsteamObject = jarray.get(i).getAsJsonObject();
App app = new SteamApp(jsteamObject.get("appid").getAsLong(), jsteamObject.get("name").toString());
apps.add(app);
//System.out.println("App[" + app.getAppid() + ", " + app.getName() + "] \n\r");
}
em.persist(apps);
em.flush();
} catch (Exception ex) {
Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我从 web 服务调用这个方法,只是为了测试它。我计划在后台使用单独的线程将其拉入。
但我做错了什么?这种持久性设置非常混乱?!?