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. 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:
@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:
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
But it gave me the following error: "The state field path 'b.genreCollection.id' cannot be resolved to a valid type."
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)
. So i just use that and string together my query with StringJoiner.