JPQL createNativeQuery加入失败

时间:2015-05-05 10:51:53

标签: java mysql jpa jpql toplink

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

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上运行。

1 个答案:

答案 0 :(得分:2)

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

web

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

'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,

    \App\Http\Middleware\FrontEnd\IpHitsCounter::class // your middleware
],