如何为多对多关联编写 HQL 查询

How to write a HQL query for a many to many association

所以我花了几个小时尝试为多对多关系编写 HQL 查询。对于我尝试过的所有查询,即使在阅读了休眠文档之后也没有任何效果。有人可以帮助我吗?提前谢谢你。

我已经尝试过内部连接、连接和外部连接,有或没有提取。我认为这个问题可能与香水 class.

中的一对多关系有关
@Query("FROM Category c INNER JOIN FETCH c.fragrances f WITH c.referencedId = 1")
List<Category> getCatalog();

类别 Class 没有 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;
]

香味Class无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;
}

试试这个:

select c from Category c join c.fragrances f where c.referencedId = :id

您可以在这里查看类似的问题:How do I do with HQL, many to many?