How to add Distinct in Hibernate Criteria

前端 未结 8 1586
耶瑟儿~
耶瑟儿~ 2020-11-29 03:58

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

相关标签:
8条回答
  • 2020-11-29 04:02

    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>.

    0 讨论(0)
  • 2020-11-29 04:03

    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();
    
    0 讨论(0)
  • 2020-11-29 04:09

    Try to use :

    cr.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    

    It work perfectly for me

    0 讨论(0)
  • 2020-11-29 04:13

    Try to use :

    Criteria criteria = 
        session.createCriteria(Test.class).setProjection(
            Projections.distinct(Projections.property("testType")));
    List<Test> rsList = criteria.list();
    
    0 讨论(0)
  • 2020-11-29 04:13

    Try

    setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)

    Criteria crit = session.createCriteria(Test.class);

    List list = crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

    0 讨论(0)
  • 2020-11-29 04:17

    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

    0 讨论(0)
提交回复
热议问题