1 Question: HQL query for Many to Many Explict relationship

Question created on Sunday February 26, 2017

I am trying to write hql for the below models.


@Entity public class Product implements Serializable {

    private static final long serialVersionUID = -3532377236419382983L;

    @GeneratedValue(strategy = GenerationType.AUTO)
    private int productId;

    @NotEmpty(message = "The product name must not be empty")
    private String productName;

    private String productCategory;

    private String productDescription;

    @JsonIgnore     @JoinTable(name="PRODUCT_SUBCATEGORY", 
    private Set<SubCategory> subCategory = new HashSet<SubCategory>(); //getter setter


public class SubCategory implements Serializable {

    private static final long serialVersionUID = 7750738516036520962L;

    @Expose(serialize = true, deserialize = true)
    private Integer subCategoryId;

    @Expose(serialize = true, deserialize = true)
    @NotEmpty(message = "The subcategory name must not be empty")
    @Size(min = 3, max = 20, message = "Minimum 3 to 20 characters allowed")
    private String subCategoryName;

    @Expose(serialize = false, deserialize = false)
    private Category category;
//getter setter

I would like to query base on subcategory table's subcategoryname to get the product data through PRODUCT_SUBCATEGORY table. Sample query like as below.

select * from product where productid in(
select psc.productid from
subcategory sc
inner join product_subcategory psc
on sc.subcategoryid=psc.subcategoryid
where sc.subcategoryname like 'men ware%');

How do I achieve the above sql in hql.

Thank you.

1 answer                              3                         
select distinct p from Product p 
join p.subCategory sc 
where sc.subCategoryName like :name
Sunday February 26, 2017
source posted here