我正在使用 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/