One to Many search using AND condition

前端 未结 1 1950
既然无缘
既然无缘 2021-01-25 10:22

I have the following product which contain many colors.

I wish to find the product which contain at least RED and GREEN.

Product class

    String id;

          


        
1条回答
  •  星月不相逢
    2021-01-25 11:04

    the idea is we select all products with the colors and count each product, then products with both colors should have a count of 2 as the number of colors

    DetachedCriteria colorCrit = DetachedCriteria.For(Product.class)
        .createAlias("colors","color")
        .add(Restriction.eq("color.color", "RED")
        .add(Restriction.eq("color.color", "GREEN")
        .SetProjection(Projections.Group("id"))
        .add(Restriction.eq(Projections.rowCount(), 2));
    
    Criteria criteria = createCriteria()
        .add(Subqueries.in("id", colorCrit)
        .list();
    

    Update:

    there is an issue for hibernate for exactly this. the last comment describes how to use.

    0 讨论(0)
提交回复
热议问题