关于 java:Hibernate Criteria with group by getting error

Hibernate Criteria with group by getting error

我有这两个引用表的实体 java 类(jos_content


我们可以使用投影来缩小选定列的范围,但是我们必须决定

  • 我们将使用表示为 object[] 的结果吗
  • 我们会将结果转换为 DTO(如果可能的话,转换为原始实体)

如果我们要进行转换,我们必须帮助转换器使用列名。它通过传递 alias

完成

1
2
3
4
5
6
7
8
9
10
PropertyProjection propProjection = Projections
   .groupProperty("content.id")
       .as("id") // the alias
   ;

contentCriteria
    .setProjection(propProjection)
    .setResultTransformer(Transformers.aliasToBean(ContentEntity.clas????s));

List<ContentEntity> groupedEntities = contentCriteria.list();

那么结果将是 ContentEntity 的列表,该列表将仅填充 id。请参阅:

  • 17.9。预测、聚合和分组

The alias() and as() methods simply wrap a projection instance in another, aliased, instance of Projection.

或者我们可以预期结果为 object[]

1
Object[] results = contentCriteria.list();

扩展:

如果我们想获取路由实体列表,我们可以将当前查询转换为 DetachedCriteria

1
2
3
4
5
DetachedCriteria grouped = DetachedCriteria.forClass(ContentEntity.class,"grouped")
    // Filter the Subquery
    .add(...
    // SELECT The User Id  
   .setProjection(propProjection)

所以,上面只会返回我们喜欢的ID,主查询会被它们过滤,同时返回完整的对象(无需转换)

1
2
Criteria query = session.createCriteria(ContentEntity.class,"content")
    .add( Subqueries.propertyIn("content.id", grouped) );

在这里检查类似的东西:Hibernate Criteria for "in subselect"