【问题标题】:Space is not allowed after parameter prefix ':' JPA参数前缀 ':' JPA 后不允许有空格
【发布时间】:2020-03-11 10:30:19
【问题描述】:
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";
        }

我得到错误:参数前缀':'后不允许有空格我试过用\:=转义,但没有用

【问题讨论】:

  • 你在哪一行得到了错误,你能分享一下堆栈跟踪吗?
  • 关于查询查询 = em.createNativeQuery(q);线。似乎 processinfo 变量包含“:”字符

标签: hibernate spring-boot jpa


【解决方案1】:

问题是你没有使用Prepared Statements,它也让你容易受到SQL注入。

    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 语句中关闭它。

【讨论】:

    猜你喜欢
    • 2015-04-10
    • 2019-06-04
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2019-06-17
    • 2019-08-11
    相关资源
    最近更新 更多