[英]Projections.countDistinct with Hibernate produces unexpected result
[英]Map hibernate projections result to java POJO model
在过去的几周里,我一直在使用spring和hibernate,并且我一直在那里学习新东西。
现在,我有一个要在Hibernate中使用Projections解决的问题。
假设有一个模型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
,这是db操作的代码:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.