Map hibernate projections result to java POJO model

无人久伴 提交于 2019-12-04 09:29:49

Never mind, I've found the solution.

  1. First we need to create alias of the associated object like so

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria("model.Person");
    criteria.createAlias("cars", "cars");
    
  2. Select the needed using Hibernate Projections

    ProjectionList projections = Projections.projectionList();
    projections.add(Projections.property("id").as("id"));
    projections.add(Projections.property("name").as("name"));
    projections.add(Projections.property("cars").as("cars"));
    
  3. Group the result based on the root entity (in this case using its id, Person.id), this is needed especially when used with aggregation to group the aggregation

    projections.add(Projections.groupProperty("id"));
    
  4. Use the aggregate function

    projections.add(Projections.min("cars.year").as("minYear"));
    projections.add(Projections.max("cars.year").as("maxYear"));
    
  5. Set the projection

    criteria.setProjection(projections);
    
  6. Use result transformer AliasToBeanResultTransformer to map the result fields (as specified in step 2 & 4) to the POJO

    criteria.setResultTransformer(new AliasToBeanResultTransformer(Person.class));
    
  7. Get the result

    List<Person> results = (List<Person>) criteria.list();
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!