One to Many search using AND condition

↘锁芯ラ 提交于 2019-12-20 05:01: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;

    List<Color> colors{};

Color class

    id

    color

kindly ignore the syntax error.

I'm able to use the following to search OR condition.

Criteria criteria = createCriteria();
criteria.createAlias("colors","colors");

List<String> colorsList = new LinkedList();
colorsList.add("GREEN");
colorsList.add("RED");
criteria.add(Restriction.in("colors.color",colorsList);

The above will give me products which has red or green in their colors BUT not products which contain at least RED AND GREEN.

Example

Product: RED GREEN - PASS
Product: RED GREEN YELLOW - PASS
Product: RED YELLOW - FAIL

Thanks in advance.


回答1:


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.



来源:https://stackoverflow.com/questions/11409302/one-to-many-search-using-and-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!