简体   繁体   中英

hiebrnate projection with distinct

I am trying to get the distinct on my column "testType" in table "Test". Also I want to get both "testType" and "testId" in my list. For that I am doing this but it doesn't applying the distinct , giving me the duplicate result.

Any idea how can I resolve this?

Session session = sessionFactory.openSession();
Criteria crit = session.createCriteria(Test.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("testType"));
proList.add(Projections.property("testId"));
crit.setProjection(proList);
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List rsList = crit.list();

Thanks in advance.

to get the distinct values of testType

Session session = sessionFactory.openSession();
List results = session.createCriteria(Test.class);
    .setProjection(Projections.distinct(Projections.property("testType")))
    .list();

but to get the id as well you can't select for it since there may be many ids for each Type, eg:

testId | testType
-----------------
1      | type1
2      | type2
3      | type1
4      | type2
6      | type3
7      | type3

what should Select Distinct(testType), testid return?

  1. (type1, 1), (type2, 2), (type3, 6)
  2. (type1, 3), (type2, 4), (type3, 7)
  3. (type1, 1), (type2, 4), (type3, 6)

1)

Session session = sessionFactory.openSession();
List results = session.createCriteria(Test.class);
    .setProjection(Projections.projectionList()
        .add(Projections.group(Projections.property("testType"))))
        .add(Projections.Min(Projections.property("testid")))))
    .list();

2)

Session session = sessionFactory.openSession();
List results = session.createCriteria(Test.class);
    .setProjection(Projections.projectionList()
        .add(Projections.group(Projections.property("testType"))))
        .add(Projections.Max(Projections.property("testid")))))
    .list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM