在尝试按顺序添加条件时,JPQL Query会出现异常

时间:2017-03-08 10:02:52

标签: java mysql jpql

我正在尝试在JPQL中执行MySql查询 这是我的MySql查询

select * from test.employee order by DEG != 'm2',DEG;   

其中test是架构名称,employee是表名,DEG包含字符串。 我在JPQL中写了这个并且异常。

EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("DBConnectionPU");
EntityManager em = emFactory.createEntityManager();
Query q = em.createQuery("SELECT em FROM Employee em ORDER BY em.deg != 'm2', em.deg");
List<Employee> list = q.getResultList();   

例外:

Exception Description: Syntax error parsing [SELECT em FROM Employee em ORDER BY em.deg != 'm2', em.deg]. 

[36, 50] The order by item is not a valid expression.
        at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1605)
        at dbconnection.DBConnection.main(DBConnection.java:39)
    Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.JPQLException
    Exception Description: Syntax error parsing [SELECT em FROM Employee em ORDER BY em.deg != 'm2', em.deg]. 
    [36, 50] The order by item is not a valid expression.
        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)
        ... 1 more   

我使用条件查询尝试了这个,它工作正常。在直接的JPQL查询中它有什么问题?我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

尝试将ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession httpSession = attr.getRequest().getSession(); System.out.println("Session ID :: "+httpSession.getId()); 更改为em.deg != 'm2'

case when