这些是类 Country
和 State
:
国家:
@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