0

我正在将 JPA 2 与 Hibernate 一起使用来构建一个在我的一生中无法正确运行的查询。如下查询:

public Integer getCountForDAR(Date _SD, Date _ED, Integer _PostId, String _Filter) {

        CriteriaBuilder cb = getEm().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery(TcDarActivities.class);        
        Root fromTcDarActivities = cq.from(TcDarActivities.class);

        Path typePath = fromTcDarActivities.get(BaseDao.TC_DAR_ACTIVITY_TYPE).get(BaseDao.TYPE_NAME);
        Path postPath = fromTcDarActivities.get(BaseDao.TC_POST).get(BaseDao.POST_ID);

        cq.select(fromTcDarActivities).where(
                cb.and(cb.between(fromTcDarActivities.get(BaseDao.DARACTIVITY_TIME), _SD, _ED),
                cb.equal(postPath, _PostId),
                cb.or(
                cb.like(fromTcDarActivities.get(BaseDao.COMMENTS), _Filter),
                cb.like(typePath, _Filter)
                )));

        TypedQuery tq = getEm().createQuery(cq);
        LOGGER.info(tq.unwrap(org.hibernate.Query.class).getQueryString());

        try
        {
            List<TcDarActivities> list = getEm().createQuery(cq).setHint("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS).getResultList();
            return list.size();
        }
        catch(Exception e) { return 0; }
    }

TC_DAR_ACTIVITY_TYPE 字段在数据库中可能为空。问题是查询仅在 TC_DAR_ACTIVITY_TYPE 和 COMMENTS 的值在日期范围内时才返回结果。有人可以在这里帮忙吗。我对此感到震惊,因为我相当确定我做对了......

谢谢韦塞尔

4

1 回答 1

0

类型和发布路径使用规范要求的内部连接。您必须为要使用左外连接的任何连接指定连接和 joinType.LEFT。

FromTcDarActivities.join(BaseDao.TC_DAR_ACTIVITY_TYPE, JoinType.LEFT).get(BaseDao.TYPE_NAME);
于 2013-07-27T11:58:05.107 回答