我有以下实体类:

@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的唯一约束是,一个帐户对于一个特定的存储库只能有一个审核记录,因此同一存储库可以有多个审核记录,每个审核记录都有不同的accountid。

我想按访问时间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);

最佳答案

尝试这个。

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

10-06 06:14