问题
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