【问题标题】:How to find the maximum value for a column in an OneToMany mapping, using HQL?如何使用 HQL 在 OneToMany 映射中查找列的最大值?
【发布时间】:2020-05-27 04:31:16
【问题描述】:

这些是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?我认为您在查询中缺少countryName 之前的实体别名
  • 哦,它有效。我实际上拥有它,但是在处理一些错误时,我搞砸了。非常感谢。
  • 酷。添加为您可以接受的答案

标签: java hibernate hql one-to-many hibernate-onetomany


【解决方案1】:

您缺少实体的别名

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 2022-01-20
    • 2021-10-17
    • 2019-10-27
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多