连接失败的 JPQL createNativeQuery

JPQL createNativeQuery with join failing

我在数据库中加入了 2 个具有外键关系的实体,但在代码中没有(将原因留到另一个问题):

em.createNativeQuery("SELECT u.* FROM user u JOIN user_community_organization uco ON "
                + "u.user_id = uco.user_id "
                + "WHERE uco.community_id = :communityId "
                + "AND lower(u.email) = :email", User.class)
                .setParameter("communityId", communityId)
                .setParameter("email", email.toLowerCase());

但查询在运行时失败:

Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
You have an error in your SQL syntax; check the manual that corresponds  to your MySQL 
server version for the right syntax to use near ':communityId AND 
lower(u.email) = :email' at line 1
Error Code: 1064
Call: SELECT u.* FROM user u JOIN user_community_organization uco ON  
u.user_id = uco.user_id WHERE uco.community_id = :communityId AND lower(u.email) = :email

我尝试了不同的变体,将参数移入和移出 ON 位,移除较低的位。没有任何效果。

在我添加连接之前:

em.createQuery("select object(o) from User as o where lower(o.email) = :email");
        q.setParameter("email", email.toLowerCase());

这个查询工作正常。

我做错了什么? 运行 在 GlassFish3.1 上,toplink 和 mySql。

您的第一个示例使用的是本机查询,但您的第二个示例使用的是 JPQL,因此您并不清楚您要做什么。我认为您的本机查询失败是因为 JPA 不支持命名参数(仅位置参数,但 Hibernate 例如支持它)。所以,试试这个

em.createNativeQuery("SELECT u.* FROM user u JOIN user_community_organization uco ON "
                + "u.user_id = uco.user_id "
                + "WHERE uco.community_id = ?1 "
                + "AND lower(u.email) = ?2", User.class)
                .setParameter(1, communityId)
                .setParameter(2, email.toLowerCase());

至于 JPQL 版本,你没有 post 实体代码所以我会猜测关系,但它看起来像这样

em.createQuery("select u from User u where lower(u.email) = :email and u.communityOrganisation.id = :communityId");
        q.setParameter("email", email.toLowerCase());
        q.setParameter("communityId", communityId);