简体   繁体   中英

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

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;
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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