1

我有两个实体:

public class Rank{
     Short value; 

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


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

有没有办法通过查询加载Picturerank字段SELECT SUM(value) from ranks where pic = ?

4

1 回答 1

0

您需要图片实体中的排名列表和返回所有排名总和的方法

@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;
     }

     ...
}
于 2013-01-24T17:19:54.347 回答