【发布时间】:2020-05-27 04:31:16
【问题描述】:
这些是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?我认为您在查询中缺少countryName之前的实体别名 -
哦,它有效。我实际上拥有它,但是在处理一些错误时,我搞砸了。非常感谢。
-
酷。添加为您可以接受的答案
标签: java hibernate hql one-to-many hibernate-onetomany