JPA查询验证数据库中是否存在输入

时间:2010-02-02 15:41:07

标签: java sql jpa

我想验证netbeans IDE中数据库中是否存在输入

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException {
  try {

               Transaction1 t = new Transaction1();
               //t.setTransactionID(12345);
               t.setFromAccNo(Integer.parseInt(request.getParameter("fromAccNo")));
               t.setFromSortCodeNo(request.getParameter("fromSortCodeNo"));
               t.setToAccNo(Integer.parseInt(request.getParameter("toAccNo")));
               t.setToSortCodeNo(request.getParameter("toSortCodeNo"));
               t.setName(request.getParameter("name"));
               t.setAmount(Double.parseDouble(request.getParameter("amount")));


               Accounts a = new Accounts();
               a.setFromAccNo(Integer.parseInt(request.getParameter("fromAccNo")));
               a.setToAccNo(Integer.parseInt(request.getParameter("toAccNo")));

               Integer youraccinput = Integer.parseInt(request.getParameter("fromAccNo"));

               EntityManager em = null;
               Query checkbothno = em.createQuery("SELECT a FROM Accounts a WHERE a.fromAccNo =:" + youraccinput);
                checkbothno.setParameter(youraccinput, a);

                if (checkbothno.getResultList().size() != 0) {
                    out.println ("Found");
                } else  {
                    out.println ("Not found");
                }

               try{
                    EntityManagerFactory emf = Persistence.createEntityManagerFactory("SWSXXPU");
                   // emf = Persistence.createEntityManagerFactory("SWSXXPU");
                    em = emf.createEntityManager();
                    em.getTransaction().begin();
                    em.persist(t);
                    em.persist(a);
                    em.getTransaction().commit();
                    request.getRequestDispatcher("ListTransaction").forward(request, response);
                 }

这不行,请尽快给出建议。如果可能的话也提供样本代码。感谢

1 个答案:

答案 0 :(得分:1)

使用此:

Query checkbothno = em.createQuery("SELECT a FROM Accounts a WHERE a.fromAccNo=:youraccinput");
checkbothno.setParameter("youraccinput", youraccinput);