Hibernate Group by Criteria Object
Posted
技术标签:
【中文标题】Hibernate Group by Criteria Object【英文标题】: 【发布时间】:2012-01-19 11:29:27 【问题描述】:我想用 Hibernate Criteria 实现以下 SQL 查询:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name <operator> value
GROUP BY column_name
我尝试使用 Hibernate Criteria 来实现这一点,但没有成功。
谁能给我一个例子,如何使用 Hibernate Criteria 来完成? 谢谢!
【问题讨论】:
【参考方案1】:例子请参考this,重点是使用groupProperty()
,以及Projections类提供的相关聚合函数。
例如:
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
它的等价条件对象是:
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
【讨论】:
【参考方案2】:GroupBy 在 Hibernate 中使用
这是生成的代码
public Map getStateCounts(final Collection ids)
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results)
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
hibernateSession.closeSession();
return stateMap;
【讨论】:
【参考方案3】:你可以使用@Ken Chan 提到的方法,如果你想要一个特定的对象列表,然后添加一行代码,例如:
session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));
List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();
【讨论】:
【参考方案4】:如果您必须使用休眠条件执行group by
,请使用projections.groupPropery
,如下所示,
@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;
【讨论】:
以上是关于Hibernate Group by Criteria Object的主要内容,如果未能解决你的问题,请参考以下文章
Hibernate使用distinct返回不重复的数据,使用group by 进行分组
Hibernate namedquery 抛出 ORA-00979: not a GROUP BY 表达式
Hibernate Native 查询在结果数组中返回了重复的结果,并在查询中添加了 group by