Criteria NHibernate中的独特查询

时间:2014-07-18 10:29:17

标签: distinct criteria-api hibernate-criteria nhibernate-criteria detachedcriteria

我需要在Criteria语言中使用相应的查询(从我的表中检索所有类别,但要区分它们):

SELECT DISTINCT categoryName 
FROM Category
WHERE CategoryID IN (
                        SELECT CategoryID 
                        FROM FoodCategory                       
                    )
ORDER BY categoryName

我有表 FoodCategory

    id   |     FoodID    | CategoryID
 --------|---------------|------------
         |               |  
         |               |  
         |               |  

实际上,CategoryID是指向此表的外键。这是类别

的表格
   CategoryID   |   categoryName   | otherField   
 ---------------|------------------|------------
                |                  |  
                |                  |  
                |                  |  

这是食物

的表格
      FoodID    |     FoodName     | otherField   
 ---------------|------------------|------------
                |                  |  
                |                  |  
                |                  |  

1 个答案:

答案 0 :(得分:0)

这样的事情可以解决问题:

public List<String> retrieveFoodCategoryNames() {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteriaQuery = builder.createQuery(String.class);

    Root<FoodCategory> root = criteriaQuery.from(FoodCategory.class);
    // by default an inner join so it will only get the categories which have their id in the FoodCategory table
    Join<FoodCategory, Category> joinCategory = root.join(FoodCategory_.category);
    Fetch<FoodCategory, Category> fetchCategory = root.fetch(FoodCategory_.category);

    Path<String> categoryNamePath = fetchCategory.get(Category_.categoryName);
    criteriaQuery.select(categoryNamePath).distinct(true);

    criteriaQuery.orderBy(builder.asc(categoryNamePath));

    return entityManager.createQuery(criteriaQuery).getResultList();
}

这不是完全相同的SQL请求,因为您使用的子查询我正在使用连接,但它似乎更适合这种特殊情况。子查询语法有点复杂,我不会在没有编译的情况下编写它! ^^

如果有什么不清楚,请告诉我: - )