[英]How to find the maximum value for a column in an OneToMany mapping, using HQL?
These are the classes Country
and State
:这些是
Country
和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: 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?检索特定国家/地区人口最多的州(也许在列表中)的 HQL 查询应该是什么?
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?正确的做法应该是什么?
You are missing the alias for entity您缺少实体的别名
select max(stlst.population) from Country cntry " +" join cntry.statelist stlst where cntry.countryName=:cNm1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.