Reputation: 2097
So I have spent several hours trying to write a HQL query for a many to many relationship. With all the queries that I have tried nothing worked even after reading the hibernate docs. Can someone please assist me? Thank you in advance.
I have tried inner join, join and outer join with or without fetch. I think the issue may be related to the one to many relationship within the fragrance class.
@Query("FROM Category c INNER JOIN FETCH c.fragrances f WITH c.referencedId = 1")
List<Category> getCatalog();
Category Class without get/setters
@Entity
public class Category extends AbstractEntity {
@Column(name = "name", nullable = false)
private String name;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "Category_has_Fragrance",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "fragrance_id")
)
@OrderBy("name")
private List<Fragrance> fragrances;
@Column(name = "referenced_id", nullable = false)
private int referencedId;
]
Fragrance Class without get/setters
@Entity
public class Fragrance extends AbstractEntity {
@Column(name = "name", nullable = false)
private String name;
@Column(name = "description", nullable = false)
private String description;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrances")
private Set<Category> categories;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrance")
private List<FragrancedProduct> fragrancedProducts;
@Column(name = "image_path")
private String imagePath;
}
Upvotes: 0
Views: 3724
Reputation: 2231
Try this:
select c from Category c join c.fragrances f where c.referencedId = :id
You can check a similar question here: How do I do with HQL, many to many?
Upvotes: 1