I'm struggling to understand how can I query all products that have specified category association.
I might need something like this
select p.* from product p
inner join product_category pc on p.product_id = pc.product_id
inner join category c on pc.category_id = c.category_id
where c.name = :categoryName;
but in HQL.
Assuming that you use the following mapping:
@Entity
@Table(name = "product")
class Product
{
@Id
@Column(name = "product_id")
private Long id;
@ManyToMany
@JoinTable(name = "product_category",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "product_id")
)
private List<Category> categories;
// getters/ setters
}
@Entity
@Table(name = "category")
class Category
{
@Id
@Column(name = "category_id")
private Long id;
@Column(name = "name")
private String name;
// getters/ setters
}
you can use the following HQL:
select p from Product
join fetch p.categories c
where c.name = :categoryName