我想使用条件编写以下查询。
我需要找到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;
}
答案 0 :(得分:0)
您可以在标准对象上使用以下内容。
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
答案 1 :(得分:0)
您应该执行类似
的操作//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实体属性/字段)添加到Projection列表(这需要支持查询中的 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&lt; Object []&gt;返回而不是List&lt; EmailDataBean&gt;,这通常不方便。要解决这个问题,您应该设置ResultTransformer
crit.setResultTransformer(Transformers.aliasToBean(EmailDataBean.class));
或者,您可以使用
代替使用投影criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
但是这不会从数据库中获取不同的行,而是让Hibernate过滤结果(删除重复项)。