• Hibernate 查询sql结果行数、查询列表的几种方法


    一、前言

    这个东西,难度几乎没有,就是繁琐。

    一条简单的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();
  • 相关阅读:
    win10应用 UWP 使用MD5算法
    win10应用 UWP 使用MD5算法
    用git上传代码到新浪云
    用git上传代码到新浪云
    redis三节点sentinel部署
    [HNOI/AHOI2018]转盘
    用git上传代码到新浪云
    Windows-universal-samples-master示例 XamlCommanding
    Windows-universal-samples-master示例 XamlCommanding
    Windows-universal-samples-master示例 XamlCommanding
  • 原文地址:https://www.cnblogs.com/grey-wolf/p/10209946.html
Copyright © 2020-2023  润新知