具有 INNER JOIN 条件的 JPA 命名查询失败

Posted

技术标签:

【中文标题】具有 INNER JOIN 条件的 JPA 命名查询失败【英文标题】:JPA Named query with INNER JOIN condition is failing 【发布时间】:2020-03-25 09:25:37 【问题描述】:

我正在尝试使用实体类中的内部连接条件创建命名查询。 但是,应用程序无法启动并出现异常。

实体:

@Entity
@Table(name = "fooentry")
@NamedQuery(name="query1", query="SELECT  foo.id, foo.name, foo.type, foo.action, foo.createdDateTime FROM FooEntity foo " +
        "INNER JOIN (SELECT  name, type, MAX(createdDateTime) AS recenttime FROM FooEntity GROUP BY  name, type) recententry " +
        "ON (foo.name = recententry.name AND foo.type = recententry.type) AND createdDateTime = recenttime AND isExported = false",
        lockMode=PESSIMISTIC_WRITE)
public class FooEntity 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    @NotNull
    private String msisdn;

    @Column(name = "type")
    @NotNull
    private String iccid;

    @Column(name = "action")
    @NotNull
    private Long inventoryActionId;

    @NotNull
    @Column(name = "is_exported")
    private Boolean isExported;

    @Column(name = "created_date_time")
    @NotNull
    private LocalDateTime createdDateTime;

    //setter and getter


例外: 应用程序无法启动并出现以下异常。

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.HibernateException: Errors in named queries: 
query1 failed because of: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 161

【问题讨论】:

【参考方案1】:

您可以尝试如下查询。它应该返回预期结果

SELECT foo.id, foo.name, foo.type, foo.action, foo.createdDateTime 
FROM FooEntity foo 
WHERE  
    foo.isExported = false AND
    EXISTS(
        SELECT recententry.name, recententry.type, MAX(recententry.createdDateTime) AS recenttime 
        FROM FooEntity recententry 
        WHERE recententry.name = foo.name AND recententry.type = foo.type 
        GROUP BY recententry.name, recententry.type 
        HAVING recententry.recenttime = foo.createdDateTime
    )

【讨论】:

以上是关于具有 INNER JOIN 条件的 JPA 命名查询失败的主要内容,如果未能解决你的问题,请参考以下文章

SQL表连接查询(inner joinfull joinleft joinright join)

Inner_join 有两个条件和区间内的区间条件

inner join(inner可省) 与 left join 之间的区别

Inner Join and Left Join 与条件的结合

Inner Join and Left Join 与条件的结合

sql中的inner join ,left join ,right join