setResultTransformer in Criteria

前端 未结 2 1952
-上瘾入骨i
-上瘾入骨i 2020-12-30 23:45

What is the use of setResultTransformer method in criteria API? Can someone explain this with a simple example? I read the javadocs but i am not able to understand them clea

2条回答
  •  遥遥无期
    2020-12-30 23:54

    The default ResultTransformer for a Criteria query which does not use setProjections() will be ROOT_ENTITY.

    If we have Student in a ManyToMany relationship to Department a query might look like this ...

        Session session = (Session) getEntityManager().getDelegate();
        Criteria crit = session.createCriteria(Student.class)
            .createAlias('departments', 'department');
    

    This query will return duplicates. But set the ResultTransformer as ...

        crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    

    Now the results will be distinct when Hibernate marshalls the results. (Or do I mean unmarshalls?)

    If you do not want Hibernate to return the query as a List but prefer to handle the results as a List then

        crit.setResultTransformer(CriteriaSpecification.PROJECTION)
    

提交回复
热议问题