java - 使用JPA在 "or"语句中为空

标签 java spring hibernate jpa spring-data-jpa

我正在使用 spring-data-jpa 的 @Query 注释构建 JPA 查询,但无法使其工作。我有两个类(setter/getters 被剥离)

public class Article {
    @Id
    @GeneratedValue
    private Integer id;

    @OneToMany(cascade = CascadeType.ALL)
    @OrderColumn(name = "review_index")
    private List<Review> reviews;
}

public class Review {
    @Id
    @GeneratedValue
    @Column(unique = true, nullable = false)
    private Integer id;

    @Column(name = "review_state")
    @Enumerated(EnumType.STRING)
    private ReviewState state;  // simple enum
}

它应该做什么:查询应该返回所有文章,要么根本没有评论,要么有评论 code> 具有状态 PASSED 的集合中的最高索引。

@Query("select distinct article from Article article "
    + "left outer join article.reviews r " // outer join to include articles without review
    // be sure to be either unreviewed or passed the review
    + "where (article.reviews is empty or article.reviews[maxindex(article.reviews)].state = 'PASSED'))"

它实际上做了什么:问题是根本没有评论的文章被排除在结果之外。似乎 article.reviews isempty 根本不被尊重。旁注:如果省略 or 语句的第二部分,则 isempty 有效。

最佳答案

从评论中提取的答案:

核心问题与路径导航“article.reviews”的隐式连接(不是左连接)有关。 这可以通过该部分的专用子选择来绕过。

select distinct article 
from Article article
left outer join article.reviews r 
where article.reviews is empty or 
    exists(
        select subArticle 
        from Article subArticle 
        where article.id = subArticle.id 
        and subArticle.reviews[maxindex(subArticle.reviews)].state = 'PASSED'
    )

关于java - 使用JPA在 "or"语句中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36570108/

相关文章:

java - 为什么在 Controller 方法上调用时 getParameterTypes 为空?

ajax - Spring 安全性 + Ajax session 超时问题

java - Hibernate @Formula 注释在 Hibernate 不恰本地插入表引用时导致 sql 异常错误

java - 如何将字符串对象重新转换为 ArrayList<Entity>?

java - Hibernate 查找表/类型的注释?

java - Jackson - 将所选字段从 JSON 映射到新类实例

java - 如何解决 : Can not find the tag library descriptor for "http://java.sun.com/jsp/jSTL/core"

java - 维护从 XML 到 Excel 文件的层次结构 - Java

java - 如何将数据持久保存到 postgres,而无需转换特定的数据类型

java - Spring Web MVC 中的嵌套 Controller