我创建了一个存储用户标记的实体
基本上我想创建一个要使用的命名查询,并且一个自动计算平均值,唯一的问题是我只希望选择的列被平均
目前表格是:
@Entity(name = "MARKING")
public class Marking implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private Person marker;
@ManyToOne
private Project project;
private String markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour,
markSectionFive, markSectionSix, markSectionSeven, markSectionEight,
markSectionNine, markSectionTen, markSectionEleven, markSectionTwelve, markSectionThirteen, markAdjust, overalMark, thirdMarker, plagorism;
我要问的是,我应该如何构建只能得出marksSectionOne的平均值的查询 - 十三
谢谢你们
编辑
我已将此添加到我的Facade中,但它似乎不对吗?
public TypedQuery<Double> markingAvg(Project id) {
System.out.println("id = " + id);
TypedQuery<Double> query = em.createQuery("select ((m.markSectionOne + m.markSectionTwo + m.markSectionThree + "
+ "m.markSectionFour + m.markSectionFive + m.markSectionSix + m.markSectionSeven +"
+ "m.markSectionEight + m.markSectionNine + m.markSectionTen + m.markSectionEleven +"
+ "m.markSectionTwelve + m.markSectionThirteen) / 13.0) from Marking m where m.project = :id", Double.class);
query.setParameter("id", id);
double avg = query.getSingleResult();
return null;
}
答案 0 :(得分:2)
第一种方法是计算数据库端的平均值,然后检索结果:
TypedQuery<Double> query = em.createQuery("select ((m.markSectionOne + ... + m.markSectionThirteen) / 13.0) from Marking m where m.id = :id", Double.class);
query.setParameter....
double avg = query.getSingleResult();
其他方法是选择您的实体,然后在java中计算平均值:
TypedQuery<Marking> query = em.createQuery("select m from Marking m where m.id = :id", Marking.class);
query.setParameter....
Marking m = query.getSingleResult();
int sum = m.getMarkSectionOne() + ... + m.getMarkSectionThirteen();
double avg = sum / 13.0;