加载与自定义查询的关联

时间:2013-01-24 16:16:02

标签: java hibernate hql hibernate-criteria

我有两个实体:

public class Rank{
     Short value; 

     @ManyToOne(fetch=FetchType.LAZY)
     Picture pic;
     ...
}


public class Picture{
      String url;
      Long rank;    // sum of all ranks' values
}

有没有办法按查询Picture加载rankSELECT SUM(value) from ranks where pic = ?字段?

1 个答案:

答案 0 :(得分:0)

你需要一个Picture实体中的Rank列表和一个返回所有等级总和的方法

@Entity
public class Rank{
    Short value; 

    @ManyToOne(fetch=FetchType.LAZY)
    Picture pic;

    public void setPic(Picture p){
        pic = p;
        p.addRank(this);
    }

    ..
}


@Entity
public class Picture{
     String url;

     @OneToMany(fetch=FetchType.LAZY)
     List<Rank> ranks;

     Long rank;    // sum of all ranks' values

     public void addRank(Rank r) {
         ranks.add(r);
     }

     public Long getRank() {
         for(Rank r : this.ranks) {
             this.rank += r.getLongValue();
         }

         return this.rank;
     }

     ...
}