Question

I have three tables one is ItemCategory,ItemMaster and Price. I am referring itemaCategoryId in ItemMaster table and like that referring itemmasterid in price. Now i have to display contents of price order by itemcategory id. This is my criteria query.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Price> cq = cb.createQuery(Price.class);
    Root<Price> root = cq.from(Price.class);
    Root<ItemMaster> itemMasterRoot = cq.from(ItemMaster.class);
    Root<ItemCategory> itemCategoryRoot = cq.from(ItemCategory.class);
    Join<ItemMaster, ItemCategory> s=itemMasterRoot.join(ItemMaster_.category);     
    Join<Price,ItemMaster> y=root.join(Price_.itemMaster);

    Path<Long> itemMasterId=root.get(Price_.itemMasterId);
    cq.select(root).where(cb.equal(root.get(Price_.priceMasterId), priceMasterId))
    .orderBy(cb.asc(itemMasterId));

    TypedQuery<Price> q = entityManager.createQuery(cq);

Above my criteria Query

Was it helpful?

Solution

If you use multiple from statements, you get the cartesian product of all entities. If you want to preserve the relationships, use join instead:

Root<Price> price = cq.from(Price.class);
Join<Price,ItemMaster> itemMaster = price.join(Price_.itemMaster);
Join<ItemMaster, ItemCategory> itemCategory = itemMaster.join(ItemMaster_.category);

However it looks like at least the second join may be useless, because you are able to access the category property directly using the getter, isn't it?:

Price aPriceResult;
ItemCategory categoryResult = aPriceResult.getItemMaster().getCategory();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top