将Hibernate投影结果映射到Java POJO模型

4

我过去几周一直在使用Spring和Hibernate,并且一直在学习新的东西。

现在我有一个问题,我想用Hibernate中的投影来解决它。

假设有一个模型Person,该模型有许多Car。以下是类定义大致如何:

public class Person implements java.io.Serializable {
    private Integer id;
    private String name;
    private List<Car> cars;
    private Integer minYear; // Transient
    private Integer maxYear; // Transient
}

public class Car implements java.io.Serializable {
    private Integer id;
    private Integer year;
}

这里的问题是,我想要获得每个Person minYear maxYear),并使它们填写他们拥有的 cars 的最早年份(最新年份)。
后来我找到了一个使用 Projections 的解决方案,但我遇到了 org.hibernate.QueryException:could not resolve property: minYear of: model.Person ,这是数据库操作的代码:
Criteria criteria = sessionFactory.getCurrentSession().createCriteria("model.Person");
            criteria.add(create(personInstance));
            criteria.createAlias("minYear", "minYear");
            criteria.setProjection(Projections.min("cars.year").as("minYear"));

有没有办法使用Projections在瞬态方法中存储聚合值,因为我尽可能地想避免使用纯SQL和HQL。

1个回答

6
没关系,我已经找到了解决方案。
  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();
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接