javahibernatehqlone-to-manyhibernate-onetomany

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


These are the classes Country and State:

Country:

 @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>();

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;

What should be the HQL query to retrieve the states (in a List perhaps) which have the highest population in a particular country?

Here's the code I have written, where, I tried to retrieve the maximum population value first, and then run through all the states in that country, to match against every population value, and add states to a list. But, while doing so, I get the error that the columns are ambiguously defined in the query.

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;
}

What should be the correct way to do it?


Solution

  • You are missing the alias for entity

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