In my database I have a Test table, with columns: testName, testType there are 2 different tests with the same type I.e \"SUN\", so I want only one of them for which I use
Use Projections.distinct.
Criteria crit = session.createCriteria(Test.class).setProjection(
Projections.distinct(Projections.projectionList()
.add(Projections.property("type"), "type") )
.setResultTransformer(Transformers.aliasToBean(YourBean.class));
List lst = crit.list();
where YourBean.class has a property "type". The returned list will be List<YourBean>
.
I finally have found out to get values of other columns:
Criteria criteria = session.createCriteria(Test.class);
ProjectionList projectionList = Projections.projectionList();
ProjectionList projectionList2 = Projections.projectionList();
projectionList2.add(Projections.distinct(projectionList.add(Projections.property("distinctColumn"), "distinctColumn")));
projectionList2.add(Projections.property("col1"), "col1");
projectionList2.add(Projections.property("col2"), "col2");
criteria.setProjection(projectionList2);
criteria.setResultTransformer(Transformers.aliasToBean(Test.class));
List list = criteria.list();
Try to use :
cr.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
It work perfectly for me
Try to use :
Criteria criteria =
session.createCriteria(Test.class).setProjection(
Projections.distinct(Projections.property("testType")));
List<Test> rsList = criteria.list();
Try
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
Criteria crit = session.createCriteria(Test.class);
List list = crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
Projections provide the result of the marked properties only. but, it creates problem for the child entities. See my post for the real problem I faced it.
Hibernate: Parent and Child relationship data structure