意外的标记 ”?”在JPA查询期间?

时间:2014-06-23 16:44:41

标签: java-ee jpa java-ee-7

我试图查询db2数据库中的Api键列表。

问题是JPA提出的实际查询有一个额外的比较字段,导致语法错误。

错误:

[ERROR   ] CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "getApikeys" on bean "BeanId(WebApiConsole#WebApiConsole.war#ConsoleREST, null)". Exception data: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140222-22988a5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.ibm.db2.jcc.am.SqlSyntaxErrorException: An unexpected token "?" was found following "KEYS t1 WHERE ( LIKE".  Expected tokens may include:  "IN".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.16.53
Error Code: -104
Call: SELECT t1.APIKEYID, t1.APIKEY, t1.CREATEDAT, t1.PROJECTID FROM DB2ADMIN.PROJECTS t0, DB2ADMIN.APIKEYS t1 WHERE ( LIKE ? AND (t0.PROJECTID = t1.PROJECTID))
    bind => [1 parameter bound]
Query: ReadAllQuery(name="Apikey.queryAllByProject" referenceClass=Apikey sql="SELECT t1.APIKEYID, t1.APIKEY, t1.CREATEDAT, t1.PROJECTID FROM DB2ADMIN.PROJECTS t0, DB2ADMIN.APIKEYS t1 WHERE ( LIKE ? AND (t0.PROJECTID = t1.PROJECTID))")

摘录。我不知道问号出现的原因。

SELECT t1.APIKEYID, t1.APIKEY, t1.CREATEDAT, t1.PROJECTID FROM DB2ADMIN.PROJECTS t0, DB2ADMIN.APIKEYS t1 WHERE ( LIKE ? AND (t0.PROJECTID = t1.PROJECTID))

命名查询:

@NamedQuery(name    = "Apikey.queryAllByProject",
            query   = "SELECT k FROM Apikey k WHERE k.project LIKE :project")

最后,这是jax-rs应用程序代码:

Project p = (Project) em.createNamedQuery("Project.queryProjectById")
        .setParameter("projectid", Integer.parseInt(projectid)).getResultList().get(0);
List<JsonObject> apikeys = em.createNamedQuery("Apikey.queryAllByProject")
                        .setParameter("project", p)
                        .getResultList();

奇怪的是,如果我将其改为以下内容,一切都会成功:

@NamedQuery(name    = "Apikey.queryAllByProject",
            query   = "SELECT k FROM Apikey k WHERE k.project.projectid LIKE :projectid")


List<JsonObject> apikeys = em.createNamedQuery("Apikey.queryAllByProject")
                        .setParameter("projectid", 10000)
                        .getResultList();

1 个答案:

答案 0 :(得分:1)

LIKE运算符不能用来比较两个实体,没有办法用SQL语言表达这个。您需要根据匹配的ID或其他标准来获取它们。另请参阅this表,其中列出了JPA运算符及其功能。