java - 连接失败的 JPQL createNativeQuery

标签 java mysql jpa jpql toplink

我在数据库中加入了 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 上运行。

最佳答案

您的第一个示例是使用 native 查询,但您的第二个示例使用的是 JPQL,因此您并不清楚您要做什么。我认为您的 native 查询失败是因为 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 版本,你没有发布实体代码所以我会猜测关系,但它看起来像这样

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

关于java - 连接失败的 JPQL createNativeQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050984/

相关文章:

php - SQL 中的插入语句

mysql - 查询以选择具有相同列值(日期)的最后一条记录

java - Spring Batch 输出记录多于输入记录

spring - 带有枚举的 QuerySyntaxException

java - java中的SQLITE时间戳,每次都返回相同的日期

java - 从java中的System.nanoTime()计算小时

php - PHP如何让用户保持登录状态1个月?

java.lang.NoSuchMethodError : javax. persistence.JoinTable.indexes()[Ljavax/persistence/Index;

java - 通过@Profile 启用 WebSecurityConfigurer 不起作用

java - RedHat 上的 tomcat 6 内存不足,但在 debian 中没有