我在 hql 中使用选择查询。但我无法在我的 API 中使用。
出现错误
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
有人可以告诉我我的 HQL 中的错误是什么吗
我的代码
Session session = SessionUtil.getSession();
//Query query = session.createQuery("from Login where email='" + email + "' and password='" + password + "'");
Query query = session.createQuery("SELECT CONCAT(p.FIRSTNAME, ' ', p.LASTNAME) as Name, a.mobile, a.email, p.patientId\n"
+ "FROM ( from login where email= '\" + email + \"' and password= '\" + password + \"') a\n"
+ " INNER JOIN\n"
+ " patientprofile p ON a.loginId= p.loginId");
List<Login> logins = query.list();
session.close();
return logins;
最佳答案
首先:\n
在查询中不被接受,因此您必须删除它们。
Query query = session.createQuery("SELECT CONCAT(p.FIRSTNAME, ' ', p.LASTNAME) as Name, a.mobile, a.email, p.patientId "
+ "FROM ( from login where email= '" + email + "' and password= '" + password + "') a "
+ " INNER JOIN "
+ " patientprofile p ON a.loginId= p.loginId");
第二:连接并不安全,您可以使用 setParameter
来避免语法错误和 SQL 注入(inject):
Query query = session.createQuery("SELECT CONCAT(p.FIRSTNAME, ' ', p.LASTNAME) as Name,"
+ "a.mobile, a.email, p.patientId "
+ "FROM ( from login where email= :email and password= :password) a "
//----------------------------------^----------------------^
+ "INNER JOIN "
+ "patientprofile p ON a.loginId= p.loginId");
query.setParameter("email", email);
query.setParameter("password", password);
第三:我真的不明白查询的这一部分(来自登录,其中电子邮件=:电子邮件和密码=:密码)
这可能会产生另一个问题,请确保您使用正确的查询!它可以是:
Query query = session.createQuery("SELECT CONCAT(p.FIRSTNAME, ' ', p.LASTNAME) as Name,"
+ "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);
第四:我想改用原生查询,因为 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 中了解更多相关信息
关于java - org.hibernate.hql.internal.ast.QuerySyntaxException :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46156116/