2017-09-12 48 views
2

我在hql中使用select查询。但我不能在我的API中使用。HQL查询中的语法错误“意外令牌”

收到错误为:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: 

有人可以告诉我笏是我的HQL

代码,供大家参考错误:

Session session = SessionUtil.getSession(); 

Query query = session.createQuery("SELECT a.mobile, a.email, p.patientId FROM (SELECT l " 
     + "from login l where email= :email and password= :password) a INNER JOIN patientprofile p ON a.loginId= p.loginId"); 
query.setParameter("email", email); 
query.setParameter("password", password); 
List<Login> logins = query.list(); 
session.close(); 
return logins; 
+1

你可以分享完整的错误@mree请 –

+0

org.hibernate.hql.internal.ast.QuerySyntaxException:意外的标记:(靠近第1行,第44列[SELECT a.mobile,a.email,p.patientId FROM( SELECT l.LoginId,l.email,l.mobile from com.innovellent.hibernate.restapi.model.Login l where email =:email and password =:password)INNER JOIN com.innovellent.hibernate.restapi.model.PatientProfile p ON a.loginId = p.loginId] – mehul

回答

1

我想用本机查询相反,因为HQL和JPQL都接受子查询只是在SELECT,WHERE或HAVING子句中,因此您可以使用:

Query query = session.createNativeQuery("SELECT a.mobile, a.email, p.patientId FROM " 
     + "(SELECT * from login l where email= :email and password= :password) a " 
     + "INNER JOIN patientprofile p ON a.loginId= p.loginId"); 
query.setParameter("email", email); 
query.setParameter("password", password); 

阅读更多关于这在JPQL documentation

Subqueries可以在WHEREHAVING子句中使用。

+1

感谢您的帮助..它的工作 – mehul

1

请注意,HQL子查询只能发生在select或where子句中。

因此,您可以使用nativeQuery,但我会建议尽可能使用HQL以避免数据库可移植性的麻烦,并利用Hibernate的SQL生成和缓存策略。 而不是原生查询,您可以使用连接方法并链接它们。

注意HQL与持久对象及其属性配合使用 .HQL查询由Hibernate翻译为常规SQL查询,后者依次对数据库执行操作。