简体   繁体   English

JPA WHERE 多对多实体子句

[英]JPA WHERE clause on many-to-many entity

I have two table, Book and Genre.我有两张桌子,书本和流派。 Each book may have many genre, and the many-to-many table only contain the Book ID and Genre ID.每本书可能有多种流派,多对多表只包含书本 ID 和流派 ID。 I want to create a filter which would filter books by it's genre(s).我想创建一个过滤器,它可以按类型过滤书籍。

  @JoinTable(name = "bookGenre", joinColumns = {
    @JoinColumn(name = "bookId", referencedColumnName = "id")}, inverseJoinColumns = {
    @JoinColumn(name = "genreId", referencedColumnName = "id")})
  @ManyToMany
  private Collection<Genre> genreCollection;

Genre Class:类型 Class:

  @Id
  @Basic(optional = false)
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Integer id;
  @Size(max = 255)
  @Column(name = "name")
  private String name;
  @Column(name = "status")
  private Integer status;
  @ManyToMany(mappedBy = "genreCollection")
  private Collection<Book> bookCollection;

This is the query that I'm trying to do on JPA:这是我试图在 JPA 上执行的查询:

SELECT b.title FROM book b
JOIN bookGenre bg on bg.bookId = b.id
JOIN genre g on bg.genreId = g.id
WHERE g.id = 1
--Filter books that have genre with id 1

I've tried the following on JPA: SELECT b FROM Book b WHERE b.genreCollection.id = 1我在 JPA 上尝试了以下操作: SELECT b FROM Book b WHERE b.genreCollection.id = 1

But it gave me the following error: "The state field path 'b.genreCollection.id' cannot be resolved to a valid type."但它给了我以下错误:“state 字段路径 'b.genreCollection.id' 无法解析为有效类型。”

EDIT: I found out that i can use native sql query with built in result set mapping to Book POJO EntityManager.createNativeQuery(query, Book.class) .编辑:我发现我可以使用原生 sql 查询和内置结果集映射到 Book POJO EntityManager.createNativeQuery(query, Book.class) So i just use that and string together my query with StringJoiner.所以我只是使用它并将我的查询与 StringJoiner 串在一起。

I think your JPA Query should be我认为您的 JPA 查询应该是

SELECT b FROM Book b INNER JOIN b.genreCollection g WHERE g.id = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM