【问题标题】:Distinct query in Criteria NHibernateCriteria NHibernate 中的不同查询
【发布时间】:2014-09-09 11:12:22
【问题描述】:

我需要用 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   
 ---------------|------------------|------------
                |                  |  
                |                  |  
                |                  |  

【问题讨论】:

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


    【解决方案1】:

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

    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 请求,因为您在我使用连接的地方使用了子查询,但它似乎更适合这种特殊情况。子查询语法稍微复杂一点,不编译就不写了! ^^

    如果有不清楚的地方请告诉我:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      相关资源
      最近更新 更多