0

我对 Hibernate 有点陌生。我必须用 Hibernate 实现以下查询。你能帮我解决这个问题吗?我在谷歌搜索,但找不到解决方案。可能是我在寻找错误的部分。

SELECT s.name state_name,
       (SELECT count (*)
          FROM male m
         WHERE     m.id = s.id male,
       (SELECT count (*)
          FROM female f
         WHERE    f.id = s.id female
  FROM state s;

我可以单独找到计数,但问题是我无法将它们全部添加到单个查询中。

查询应该找到以下结果:

state_name    male    female
ABCD          10      5
MNOP          7       15

非常感谢任何帮助。谢谢。

以下是我的方法:

public void populateCountForStateByGender() {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<PopulationCount> query = criteriaBuilder.createQuery(PopulationCount.class);

        query = getQueryWithSummaryColumns(query, criteriaBuilder);

        TypedQuery<PopulationCount> typedQuery = entityManager.createQuery(query);
        List<PopulationCount> rows = typedQuery.getResultList();

    }

private <T> CriteriaQuery<T> getQueryWithSummaryColumns(CriteriaQuery<T> query, CriteriaBuilder cb) {
    Root<State> root = query.from(State.class);

    Root<Population> populationOccurrence = query.from(Population.class);


    Expression<Short> statusOfOccurrence = errorOccurrence.get(Population_.gender);

    LinkedList<Selection<? extends Object>> columns = new LinkedList<Selection<? extends Object>>();

    Predicate correlatePredicate = cb.equal(
        populationOccurrence.get(Population_.stateId), root);

    columns.add(root.get(State_.id));
    columns.add(cb.count((cb.selectCase().when(
        cb.equal(statusOfOccurrence, GenderStatus.MALE.getCodeValue()), 1L))));
    columns.add(cb.count((cb.selectCase().when(
        cb.equal(statusOfOccurrence, GenderStatus.FEMALE.getCodeValue()), 1L))));

    query.where(correlatePredicate);
    query.multiselect(columns);

    return query;
}

现在TypedQuery<PopulationCount> typedQuery = entityManager.createQuery(query); 给我 NullPointerException。

仅供参考:Population 和 State 是实体类,PopulationCount 是一个带有 Getter 和 Setter 的 POJO,用于存储结果

4

1 回答 1

1

一种方法是使用 createSQLQuery:

String sql = //.. your sql as per above
List result = session.createSQLQuery(sql).addEntity(StateSummary.class).list();

这是假设您有一个 StateSummary 类来映射生成的结果集,如下所示:

@Entity
public class StateSummary {
  private String state_name;
  private int male;
  private int female;
  // getters & setters..
}
于 2013-08-12T02:48:36.753 回答