我有以下实体类:
@Entity
@Table(name = "auditrecord", uniqueConstraints = { @UniqueConstraint(columnNames = {
"accountid", "repositoryid" }) })
public class AuditRecordEntity {
private UUID accountId;
private UUID repositoryId;
private Date accessTime;
@Column(name = "accountid", nullable = false, updatable = false)
public UUID getAccountId() {
return accountId;
}
@Column(name = "repositoryid", nullable = false, updatable = false)
public UUID getRepositoryId() {
return repositoryId;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "accesstime", nullable = false, updatable = true)
public Date getAccessTime() {
return accessTime;
}
// setters for above fields
}
请注意accountId + repositoryId上的唯一约束,一个帐户只能有一个特定仓库的审计记录,因此同一个仓库可能有多个审计记录,每个审计记录都有不同的值。
我希望获得每个特定仓库的最新/最新的访问时间 AuditRecordEntitys列表,最好使用条件API。
需要插入下面的空格:
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<AuditRecordEntity> root = criteriaQuery.from(AuditRecordEntity.class);
criteriaQuery.select(root);
// here
List<Predicate> predicates = new ArrayList<Predicate>();
// add predicates here.
entitySearchCriteria.addPredicates(predicates);
addEntityCriteria(criteriaBuilder, criteriaQuery, root, entitySearchCriteria, null, null);
return getPagedByQuery(criteriaQuery, pageSize, pageNumber);
答案 0 :(得分:1)
试试这个。
DetachedCriteria maxDateQuery = DetachedCriteria.forClass(AuditRecordEntity.class);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max("accessTime"));
proj.add(Projections.groupProperty("repositoryId"));
maxDateQuery.setProjection(proj);
我不确定这是否有用,这应该会让你知道如何做到这一点。
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<AuditRecordEntity> root = criteriaQuery.from(AuditRecordEntity.class);
Expression<Date> accessTime = root.get("accessTime");
criteriaQuery.select(criteriaBuilder.max(accessTime));
criteriaQuery.groupBy(root.get("userId"));
//other code
参考:Answer