【问题标题】:JPQL createNativeQuery with join failing连接失败的 JPQL createNativeQuery
【发布时间】:2015-07-15 01:40:26
【问题描述】:

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

【问题讨论】:

  • 您确定要向我们展示真实代码吗? SQL 日志显示参数没有被替换。为什么使用原生 SQL 查询而不是 JPQL 查询?
  • @JB Nizet 这是我下一个问题的主题 - 涉及 3 路链接,我无法使用 jpql 让它工作,所以在此期间我正在这样做老式的方式。

标签: java mysql jpa jpql toplink


【解决方案1】:

您的第一个示例使用本机查询,但您的第二个示例使用 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 版本,你没有发布实体代码,所以我会猜测一下关系,但它看起来像这样

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

【讨论】:

  • 哎呀,我怎么会错过呢?谢谢。
猜你喜欢
  • 2011-11-24
  • 2016-01-22
  • 2016-05-13
  • 2014-11-22
  • 2016-03-10
  • 1970-01-01
  • 2015-03-04
  • 2011-11-04
相关资源
最近更新 更多