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

时间:2017-09-11 12:44:36

标签: java sql hibernate

我在hql中使用select查询。但我不能在我的API中使用。

将错误视为

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

有人能告诉我wat是My 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;

1 个答案:

答案 0 :(得分:1)

首先:\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注入:

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);

第三:我真的不明白查询( 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 "
            + "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);

Forth:我想使用本机查询,因为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

中详细了解此信息