如何在Spring Data JPA存储库方法的@Query方法中的JPA查询中添加条件where子句?
例如,
@Query("select student from Student student #{:rollNumber == '123' ? 'where student.rollNumber > 123' : ''} ")
List<Student> findStudents(@Param("rollNumber") int rollNumber)
我遇到以下异常: -
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing [select student from Student student #{:rollNumber == '123' ? 'where student.rollNumber > 123' : ''} ].
[62, 63] The FROM clause has 'Student student' and '#{:rollNumber =' that are not separated by a comma.
[104, 105] The identification variable '=' cannot be a reserved word.
[105, 172] The query contains a malformed ending.
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:155)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:334)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.populateQueryImp(HermesParser.java:278)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildQuery(HermesParser.java:163)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:142)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:116)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:102)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:86)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1603)
... 74 more
答案 0 :(得分:0)
我不确定Spring数据当前是否会向SpeL解析器注入查询参数。 你可以尝试这样的事情:
@Query("select student from Student student where :rollNumber==123 or student.rollNumber > 123 ")
List<Student> findStudents(@Param("rollNumber") int rollNumber)