Reputation: 147
Here I am facing an issue in hibernate criteria usage, I have created criteria for multiple tables and added restrictions but the output is not as expected
My code:
final Criteria crit = session2.createCriteria(Item.class, "item");
crit.createCriteria("itemvalues", "values");
crit.createCriteria("categoryitemses", "catItems");
crit.createCriteria("catItems.category", "cat");
crit.createCriteria("cat.categorytype", "catType");
crit.createCriteria("cat.categoryproducts", "catProd");
crit.createCriteria("catProd.product", "prod");
crit.createCriteria("prod.customer", "cust");
crit.add(Restrictions.eq("catType.id", id));
crit.add(Restrictions.eq("cust.id", custId));
crit.add(Restrictions.eq("values.inputkey", "previewimage"));
crit.addOrder(Order.asc("item.id"));
In Item.java I have the following properties
private Itemtype itemtype;
private String name;
private String description;
private Set<Itemvalue> itemvalues = new HashSet<Itemvalue>(0);
private Set<Categoryitems> categoryitemses = new HashSet<Categoryitems>(0);
ItemValue table contain a field name inputkey which contains entries like previewimage and content but all I need is only to retrieve previewimage inputkeys.
But in the output inputkeys comes with some other values also.
I have found that the query generated by hibernate is running correctly and gives output as expected but after that queries there are several other queries also executed when I retrieve the itemvalue using the set
final Set<Itemvalue> itemValues = itemList.get(innerIndex).getItemvalues();
final Iterator<Itemvalue> itemVals = itemValues.iterator();
while(itemVals.hasNext()) {
jobj.put("Location", itemVals.next().getValue());
}
Here in the line itemValues.iterator hibernate query executed 17 times since the overall output is 17 items and each item it fetches the itemvalue but omits the condition given earlier
crit.add(Restrictions.eq("values.inputkey", "previewimage"));
What I am missing here? Anyone please help me to resolve this!
Thanks in advance,
Karthi.
Upvotes: 1
Views: 1428
Reputation: 10994
Your original query uses the Restrictions.eq("values.inputkey", "previewimage")
restriction to filter out Item
objects and not Itemvalue
objects.
When getItemvalues()
is called the Hibernate collection mapping is used to retrieve the objects and not the original query. If there is nothing special about the collection mapping, the unfiltered collection of related item values objects will be returned.
You could try to configure a filter on the collection mapping or just execute a new criteria for each item to retrieve the filtered desired itemvalue collection.
Upvotes: 1