如何使用 HQL 查找 OneToMany 映射中列的最大值?

How to find the maximum value for a column in an OneToMany mapping, using HQL?

这些是 类 CountryState:

国家:

 @Entity
    @Table(name="Country")
    public class Country{
        @Id
        private String countryName;
        private String currency;
        private String capital;
        @OneToMany(mappedBy="country", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
        private List<State> statelist = new ArrayList<State>();

州:

@Entity
 @Table(name="State")
 public class State{
     @Id
     private String stateName;
     private String language;
     private long population;
     @ManyToOne
     @JoinColumn(name="countryName")
     private Country country;

检索特定国家/地区人口最多的州(也许在列表中)的 HQL 查询应该是什么?

这是我编写的代码,其中,我尝试首先检索最大人口值,然后 运行 通过该国家/地区的所有州,以匹配每个人口值,并将州添加到一个列表。但是,在这样做的同时,我得到了列在查询中定义不明确的错误。

public List<State> stateWithMaxPopulation(String countryName){
    List<State> l = new ArrayList<State>();
    Country ctr = (Country)session.get(Country.class,countryName);
    String hql = "select max(stlst.population) from Country cntry "
    +" join cntry.statelist stlst where countryName=:cNm";

    Query query = session.createQuery(hql);
    query.setParameter("cNm", countryName);
    Long maxPop = (Long)query.uniqueResult();

    for(State st : ctr.getStatelist()){
        if(st.getPopulation() == maxPop)
            l.add(st);
    }

    return l;
}

正确的做法应该是什么?

您缺少实体

的别名

select max(stlst.population) from Country cntry " +" join cntry.statelist stlst where cntry.countryName=:cNm1