我有一个名为Vote的课程:
@Table(name = "PHY_VOTE")
public class VoteEntity extends BaseEntity<Long> implements Comparable {
public static final String TITLE = "title";
public static final String VALUE = "value";
public static final String USER = "user";
private String title;
private String value;
private UserEntity user;
public VoteEntity() {}
public VoteEntity(Long id) {
setId(id);
}
public VoteEntity(String title, String value, UserEntity user) {
this.title = title;
this.value = value;
this.user = user;
}
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "VOTE_ID")
@Override
public Long getId() {
return super.getId();
}
@FilterProperty(operation = FilterProperty.ILIKE)
@Column(name = "TITLE", nullable = false, length = 100)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@FilterProperty(operation = FilterProperty.ILIKE)
@Column(name = "VALUE", nullable = false, length = 4)
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@ManyToOne
@JoinColumn(name = "USER_ID", foreignKey = @ForeignKey(name = "PYH_VOTE_USER_FK"))
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
@Transient
@Override
public String getOptionsTitleProperty() {
return TITLE;
}
}
如何使用Criteria创建以下命令?
从PHY_VOTE t GROUP BY t.TITLE中选择t.TITLE,ROUND(SUM(t.VALUE)/ COUNT(t.TITLE),2)值
答案 0 :(得分:0)
您可以考虑使用FluentJPA来做到这一点:
public AverageByTitle getAverageByTitle() {
FluentQuery query = FluentJPA.SQL((VoteEntity t) -> {
Alias<Number> avg = alias(ROUND(SUM(INT.raw(t.getValue())) / COUNT(t.getTitle()), 2),
AverageByTitle::getAverage);
SELECT(t.getTitle(), avg);
FROM(t);
GROUP(BY(t.getTitle()));
});
return query.createQuery(em, AverageByTitle.class).getSingleResult();
}
// declarations
public static final DataType<Integer> INT = DataTypes.INT;
@Tuple
@Data // lombok
public static class AverageByTitle {
private String title;
private float average;
}
产生以下SQL:
SELECT t0.TITLE, ROUND((SUM(t0.VALUE) / COUNT(t0.TITLE)), 2) AS average
FROM PHY_VOTE t0
GROUP BY t0.TITLE