用于获取一对多关系中某些项的HQL查询

时间:2017-11-12 23:21:42

标签: java hibernate jpa hql jpql

我在互联网上搜索过,但没有找到答案。

我在两个类之间有一个oneToMany关系,我希望获得列表的一部分。

@Entity
@Table(name = "author")
class Author {
     @Id
     private Long id;

     @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
     @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "id")
     private List<Book> books = new ArrayList<>();

}

@Entity
@Table(name="book")
class Book {

    @Column
    private Integer year;

    @Column
    private Integer position;

}

我希望获得特定年份的所有书籍,并且低于特定作者的特定位置

@Query(From Book b where b.year=:year and b.position<:position and b.authorId=:id)
List<Book> getAllBooks(Integer year, Integer position, Long id)

我也尝试了

@Query(From Book b where b.year=:year and b.position<:position and b.id in (select a.books.id from author a where a.id:=id)

感谢您帮助我

1 个答案:

答案 0 :(得分:0)

如果您尝试使用JPQL设置查询,对我来说看起来应该是......

@Query("SELECT b FROM Book b WHERE b.year = :year and b.position < :position and b.authorId = :id")

更新

抱歉 - 我之前通过复制和修改你的第一个例子回答。我错过了加入。

这可能有用......

@Query("SELECT a.books b FROM Author a WHERE b.year = :year AND b.position < :position AND a.authorId = :id")

你也可以试试这个...

@Query("SELECT b FROM Book b WHERE b.year = :year AND b.position < :position AND b IN (SELECT a.books FROM Author a WHERE a.id = :id")