Question

I have two domain as follows

WishList{
  int id;
  @ManyToOne
  Item item;
}

Item{
 int id;
 int productCategory;
 String productName;
}

Now Suppose I have product

(1,1,Mobile )
(2,2,Microwave)
(3,3,flashDrive)
(4,1, Monitor)

Now How do I group by query in WishList so that I get

(1,1,Mobile )
(4,1, Monitor)
(2,2,Microwave)
(3,3,flashDrive)

I am using Hibernate Criteria

How to do this??

Was it helpful?

Solution

If you are using hibernate Criteria you can create alias for Item like

Criteria criteria = hibernetSession.createCriteria(WishList.class);
criteria.createAlias("item", "itemAlias")
.setProjection(Projections.projectionList()
.add(Projections.property("id"),"id")
.add(Projections.property("itemAlias.id"),"itemAlias.id")
.add(Projections.property("itemAlias.productCategory"),"itemAlias.productCategory")
.add(Projections.property("itemAlias.productName"),"itemAlias.productName")
.add(Projections.groupProperty("itemAlias.productName")))
.setResultTransformer(Transformers.aliasToBean(WishList.class));
List<WishList> itemList = criteria.list();

and use Projections for grouping

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top