【问题标题】:JPA Named query with INNER JOIN condition is failing具有 INNER JOIN 条件的 JPA 命名查询失败
【发布时间】: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

【问题讨论】:

    标签: java hibernate jpa spring-data-jpa named-query


    【解决方案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
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2018-06-26
      • 2013-01-31
      • 1970-01-01
      • 2022-12-11
      • 2011-05-03
      相关资源
      最近更新 更多