参数前缀':'JPA后不允许有空格

时间:2019-11-15 09:39:25

标签: hibernate spring-boot jpa

This is my query:

EntityManager em = null;
        EntityTransaction et = null;
        try {
            em = entityManagerFactory.createEntityManager();
            et = em.getTransaction();
            et.begin();
            String q = "UPDATE naeb_application_processes SET process_info="+processinfo+", status=1 WHERE application_id="+naebappid+" AND process_id=44";
            System.out.println(q);
            Query query = em.createNativeQuery(q);
            query.executeUpdate();
            et.commit();
        } catch (Exception e) {
            if(et != null) {
                et.rollback();
            }
            // TODO: handle exception
            e.printStackTrace();
            resp = "FAILED";
        }
        finally {
            em.close();
            resp = "OK";
        }

我收到错误:参数前缀':'后不允许使用空格,我尝试使用\:=进行转义,但没有成功

1 个答案:

答案 0 :(得分:1)

问题是您没有使用Prepared Statements,这也使您容易受到SQL注入的攻击。<​​/ p>

    EntityManager em = entityManagerFactory.createEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        String q = "UPDATE naeb_application_processes SET process_info=:pinfo, status=1 WHERE application_id=:appid AND process_id = :pid";
        System.out.println(q);
        Query query = em.createNativeQuery(q);
        query.setParameter("pinfo", processinfo);
        query.setParameter("appid", naebappid);
        query.setParameter("pid", 44); //or 44L depending on your database and layout
        query.executeUpdate();
        et.commit();
    } catch (Exception e) {
        if(et != null) {
            et.rollback();
        }
        // TODO: handle exception
        e.printStackTrace();
        resp = "FAILED";
    }
    finally {
        em.close();
        resp = "OK";
    }

来自外部的每个参数都必须在查询中添加为名称,以:开头,并且应该如上所示简单。然后,您使用query.setParameter将这些参数传递到查询中。始终遵循此做法以确保您的数据安全。

您应该做的另一件事是确保为每个HTTP请求(而不是为每个查询)仅创建一个EntityManager,并始终在这样的try-finally语句中将其关闭。