【问题标题】:Writing distinct in hibernate criteria在休眠标准中写不同
【发布时间】:2016-10-09 16:19:35
【问题描述】:

我想使用条件编写以下查询。

我需要找到 distinct 行并在 where 子句中使用当前日期。如何在 Criteria 中实现这一点。

SELECT DISTINCT *
FROM EMAIL_PROGRAM
WHERE CURRENT_DATE >=PGM_START_DT
AND CURRENT_DATE   <= PGM_END_DT
AND EMAIL_PGM_FLG     ='Y'
AND EMAIL_PGM_DESC  IS NOT NULL
and RGN_CD = 'US';

下面是我需要应用的代码。

SessionFactory factory = null;
    Session session = null;
    try {
        factory = getSessionFactory();
        session = factory.openSession();

        final Criteria criteria = session
                .createCriteria(EmailDataBean.class);
        returnList = criteria.list();
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new DAOException(e);
    } finally {
        DBUtil.close(factory, session);
    }
    if (logger.isInfoEnabled()) {
        logger.info(LOG_METHOD_EXIT);
    }
    return returnList;
}

【问题讨论】:

    标签: java hibernate hibernate-criteria


    【解决方案1】:

    你可以在你的标准对象上使用下面。

    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    

    【讨论】:

      【解决方案2】:

      你应该做类似的事情

      //first add conditions in the where clause (you should use property names as defined in your Hbernate entities , not column names in your DB)
      criteria.add(Restrictions.ge("PGM_START_DT", startDt));
      criteria.add(Restrictions.le("PGM_END_DT", endDt));
      criteria.add(Restrictions.eq("EMAIL_PGM_FLG", "Y"));
      criteria.add(Restrictions.isNotNull("EMAIL_PGM_DESC"));
      criteria.add(Restrictions.eq("RGN_CD", "US"));
      

      现在,将每一列(即 Hibernate 实体属性/字段)添加到投影列表(这是在查询中支持 distinct 所必需的)

      ProjectionList pList = Projections.projectionList();
      pList.add(Projections.property("PGM_START_DT"), "PGM_START_DT");
      pList.add(Projections.property("PGM_END_DT"), "PGM_END_DT");
      // add all the other properties (columns) and then have the Projections.distinct method act on the entire row (all the columns)
      criteria.setProjection(Projections.distinct(pList));
      

      默认情况下,使用 Projections 会以 List 而不是 List 的形式返回结果,这通常不方便。为了解决这个问题,你应该设置一个 ResultTransformer

      crit.setResultTransformer(Transformers.aliasToBean(EmailDataBean.class));
      

      或者,您可以使用

      ,而不是使用 Projections
      criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
      

      但这不会从数据库中获取不同的行,而是让 Hibernate 过滤结果(删除重复项)。

      【讨论】:

        猜你喜欢
        • 2012-05-06
        • 1970-01-01
        • 2018-01-01
        • 2011-10-09
        • 2012-12-24
        • 2017-01-12
        • 2021-10-19
        相关资源
        最近更新 更多