我正在替换下面的sql查询并使用entitymanager criteriabuilder。我查看了其他博客和文档,但还没有成功。
选择MIN(creation_date(、MAX(creation_date(、COUNT(*(、source FROM creation_tbl,其中creation_date>=?GROUP BY来源;
我目前的方法
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Feed> criteriaQuery = criteriaBuilder.createQuery(Feed.class);
Root<Entity> root = criteriaQuery.from(Entity.class);
Expression es = root.<Date>get("creation_date");
criteriaQuery.where(criteriaBuilder.greaterThanOrEqualTo(es, dateSql));
criteriaQuery.multiselect(criteriaBuilder.greatest(root.<Date>get("creation_date")),
criteriaBuilder.least(root.<Date>get("creation_date")),
root.get("source"),
criteriaBuilder.count(root)).groupBy(root.get("source"));
Feed resultlist = entityManager.createQuery(criteriaQuery).getSingleResult();
System.out.println(resultlist);
ETL类
@Entity
@Table(name = "creation_tbl", schema = "test")
public class ETL implements Serializable {
private static final long serialVersionUID = 3940341617988134707L;
@Id
@GeneratedValue
private long id;
@Temporal(TemporalType.DATE)
@Column(name = "creation_date")
private Date creation_date;
@Column(name = "source")
private String source;
public ETL() {}
public Date getCreation_date() {
return creation_date;
}
public void setCreation_date(Date creation_date) {
this.creation_date = creation_date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
}
饲料类
@Entity
public class Feed implements Serializable {
private static final long serialVersionUID = 3940341617988134707L;
@Id
@GeneratedValue
private long id;
@Temporal(TemporalType.DATE)
@Column(name = "max")
private Date creationDateMax;
@Temporal(TemporalType.DATE)
@Column(name = "min")
private Date creationDateMin;
@Column(name = "source")
private String source;
@Column(name = "count")
private Long count;
public Feed(long id, Date creationDateMax, Date creationDateMin, String source, Long count) {
this.id = id;
this.creationDateMax = creationDateMax;
this.creationDateMin = creationDateMin;
this.source = source;
this.count = count;
}
public Feed() {}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Date getCreationDateMax() {
return creationDateMax;
}
public void setCreationDateMax(Date creationDateMax) {
this.creationDateMax = creationDateMax;
}
public Date getCreationDateMin() {
return creationDateMin;
}
public void setCreationDateMin(Date creationDateMin) {
this.creationDateMin = creationDateMin;
}
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
}
错误消息-
org.hibernate.PropertyNotFoundException:类中没有合适的构造函数:Feed
查询只选择4个字段,但Feed
构造函数需要5个字段:缺少long id
。
因此,要么从构造函数中删除该参数,要么在分组时选择一个额外的聚合id
。
p/s:Feed
看起来像DTO而不是实体,您不需要注释这些字段