2012-11-27 81 views
2

所以我有以下代碼休眠奇怪的行爲爲行計數投影

DetachedCriteria subquery = DetachedCriteria.forClass(Component.class); 
    subquery.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 
    subquery.createAlias("files", "files"); 
    subquery.createAlias("files.review", "review"); 
    subquery.createAlias("review.observers", "observer", Criteria.LEFT_JOIN); 
    subquery.add(Restrictions.or(Restrictions.eq("review.owner", user), Restrictions.eq("observer.id", user.getId()))); 
    subquery.setProjection(Projections.groupProperty("review.id")); 

    DetachedCriteria subquery2 = DetachedCriteria.forClass(ReviewNotification.class); 
    subquery2.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 
    subquery2.add(Subqueries.propertyIn("review", subquery)); 
    subquery2.add(Restrictions.eq("reviewer", user)); 
    subquery2.setProjection(Projections.groupProperty("review")); 

    Criteria criteria = session.createCriteria(Component.class); 
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 
    criteria.createAlias("files", "files"); 
    criteria.createAlias("files.review", "review"); 
    criteria.add(Subqueries.propertyIn("review.id", subquery2)); 

現在我problme是,如果我做了以下我得到2作爲返回值(這是正確的)

List<Component> list = (List<Component>) criteria.list(); 
    for (Component reviewNotification : list) { 
     System.out.println(reviewNotification); 
    } 
    return new Long(list.size()); 

但如果我這樣做

criteria.setProjection(Projections.rowCount()); 
    return (Long) criteria.uniqueResult(); 

我得到4

任何人都有任何想法爲什麼行數失敗?

我剛纔想別的

criteria.setProjection(Projections.countDistinct("id")); 

,這也適用。那麼有誰知道發生了什麼?我想這個問題來自criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);我錯了嗎?

感謝援助

回答

1

我看來,法setProjection覆蓋

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 

這可以解釋爲什麼返回數據不是唯一