一、前言
这个东西,难度几乎没有,就是繁琐。
一条简单的select count(*) from table_name
都能有多种书写方式。
总是忘,这里记录下。
一 、通过Criteria 查询
查询行数:
Criteria criteriaCount = getCriteria(); criteriaCount = criteriaCount.add(Restrictions.eq("dispatchTaskId", dispatchTaskId)); criteriaCount.setProjection(Projections.rowCount()); Integer totalCount = ((Long) criteriaCount.uniqueResult()).intValue();
查询列表:
Criteria criteria = getCriteria(); criteria.add(Restrictions.eq("eventId", eventInformationId)); List<EventTaskAssignment> list = criteria.list();
二、通过原生sql查询
查询行数:
SQLQuery queryCount = getSession().createSQLQuery("SELECT COUNT(*) FROM incidentInformation WHERE ii.incidentInformationId = :incidentInformationId AND dti.taskstate = :taskstate"); queryCount.setParameter("incidentInformationId", incidentInformationId); queryCount.setParameter("taskstate", ETaskStatus.STATUS_INIT.getStatusValue()); int count = ((BigDecimal) queryCount.uniqueResult()).intValue(); return count;
查询列表:
1、返回的item为数据库表对应po
SQLQuery query = getSession().createSQLQuery(sqlQuery); query.setParameter("userId", userId); query.addEntity(EventTaskAssignment.class); List<EventTaskAssignment> items = query.list();
2、返回的item为vo
SQLQuery query = getSession().createSQLQuery(sqlBuffer.toString()); query.setParameter("eventInformationId", eventInformationId); query.addScalar("userId", StandardBasicTypes.STRING); query.addScalar("userName", StandardBasicTypes.STRING); query.setResultTransformer(Transformers.aliasToBean(UserRoles.class)); List<UserRoles> list = query.list();
三、通过hibernate的查询语言查询
String countHql = "select count(*) from a where and a.approveResult = :approveResult and a.approverId = :approverId"; Query countQuery = getSession().createQuery(countHql); countQuery.setParameter("approverId", approverId); int count = ((Long) countQuery.uniqueResult()).intValue();