尝试创建查询时出现MismatchedTokenException

时间:2013-07-14 04:42:47

标签: java jpa antlr jpql

假设我有这个字符串(它是一个JPQL查询 - 使用实体类正确替换表和列名称)

//The actual string is auto-generated, but this is just an example:
String sql =
 "select la.laNo,la.status " +
 "from LA la " +
 "where (la.cc,la.laNo) in (" +
 "select lap.cc,lap.laNo " +
 "from LAP lap " +
 "where lap.paNo = '145'" +
 ")";

当我尝试做的时候:

Query q = org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(sql);

我得到了例外(为简洁起见,已删除了一些行):

Exception Description: Syntax error parsing the query [select la.laNo,la.status from LA la where (la.cc,la.laNo) in (select lap.cc,lap.laNo from LAP lap where lap.paNo = '145')], line 1, column 48: syntax error at [,].
Internal Exception: MismatchedTokenException(81!=84)
        at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1375)
Caused by: Exception [EclipseLink-8024] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.JPQLException
Internal Exception: MismatchedTokenException(81!=84)
        at org.eclipse.persistence.exceptions.JPQLException.syntaxErrorAt(JPQLException.java:362)
        at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.handleRecognitionException(JPQLParser.java:301)
     ...at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.arithmeticPrimary(JPQLParser.java:17303)
     ...at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.parse(JPQLParser.java:130)
     ...at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:207)
     ...at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:134)
     ...at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1373)
        ... 13 more
Caused by: MismatchedTokenException(81!=84)
        at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.mismatch(Unknown Source)
        at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.match(Unknown Source)
        at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.arithmeticPrimary(JPQLParser.java:17279)
        ... 32 more

SQL 语法正确,并且在我在数据库管理器中运行时可以正确返回结果。那么问题出在哪里呢?

更新
做了一些测试,显然,这有效:

String sql =
 "select la.laNo,la.status " +
 "from LA la " +
 "where la.cc in (" +
 "select lap.cc " +
 "from LAP lap " +
 "where lap.paNo = '145'" +
 ") " +
 "and la.laNo in (" +
 "select lap1.laNo " +
 "from LAP lap1 " +
 "where lap1.paNo = '145'" +
 ")";

为什么不选择多列?

2 个答案:

答案 0 :(得分:1)

JPQL不支持带有IN的数组,但现在EclipseLink 2.5支持此功能。

请参阅, http://java-persistence-performance.blogspot.com/2013/06/eclipselink-supports-hql-and-several.html

答案 1 :(得分:0)

createQuery()期望JPQL查询作为参数,而不是SQL查询。使用createNativeQuery()传递并执行SQL查询。