在过去的几周里,我一直在使用 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;
}
这里的问题是我想得到minYear
(maxYear
) 每个Person
由最早年份(最近年份)填写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。
没关系,我已经找到解决方案了。
-
首先我们需要像这样创建关联对象的别名
Criteria criteria = sessionFactory.getCurrentSession().createCriteria("model.Person");
criteria.createAlias("cars", "cars");
-
使用 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"));
-
根据根实体对结果进行分组(在本例中使用其 id,Person.id),这在与聚合一起使用以对聚合进行分组时尤其需要
projections.add(Projections.groupProperty("id"));
-
使用聚合函数
projections.add(Projections.min("cars.year").as("minYear"));
projections.add(Projections.max("cars.year").as("maxYear"));
-
设置投影
criteria.setProjection(projections);
-
使用结果转换器AliasToBeanResultTransformer
将结果字段(如步骤 2 和 4 中指定)映射到 POJO
criteria.setResultTransformer(new AliasToBeanResultTransformer(Person.class));
-
得到结果
List<Person> results = (List<Person>) criteria.list();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)