How to return a list of specific type instead of List<Object[]> in Hibernate?

前端 未结 5 657
太阳男子
太阳男子 2020-12-06 02:27

I have tree of classes:

classA {  
      classB b;  
      classC c;
      .....
} 

I have HQL query like this:



        
5条回答
  •  北海茫月
    2020-12-06 02:51

    If you use Hibernate 5.x, you can use a ResultTransformer, as, e.g., described in this blog post. Note that ResultTransformer will be @Deprecated in Hibernate 6.

    Applied to your scenario:

    List classDDTOs = entityManager
    .createQuery(
        "SELECT a.field1, b.field2, c.field3, c.field4 " +
        "FROM a LEFT OUTER JOIN b ON a.id = b.fk " +
        "LEFT OUTER JOIN c ON b.id = c.fk")
    .unwrap( org.hibernate.query.Query.class )
    .setResultTransformer( 
        new ResultTransformer() {
            @Override
            public Object transformTuple(
                Object[] tuple, 
                String[] aliases) {
                return new classD(
                    (Type1) tuple[0],
                    (Type2) tuple[1],
                    (Type3) tuple[1],
                );
            }
    
            @Override
            public List transformList(List collection) {
                return collection;
            }
        } 
    )
    .getResultList();
    

    The above code assumes classD has a constructor classD(Type1, Type2, Type3).

    An advantage of this approach is that it lets you define the ResultTransformer once and allows you to reuse it in all queries with the same result type.

提交回复
热议问题