使用涉及日期限制的 JPA2 使用 EntityManger 重写 Hibernate SessionFactory 查询

Rewriting a Hibernate SessionFactory Query with EntityManger using JPA2 involving Date restrictions

我有一个查询要用较旧的 Hibernate 编写(利用 SessionFactory bean)。但是,我已经转向 Spring Boot,现在正在使用 JPA 2,它本质上看起来像是 Hibernate 之上的抽象层。谁能指导我如何添加限制?我相信我现在必须将 EntityManager bean 与 JPA 一起使用。这是较旧的查询。

@Override
@SuppressWarnings("unchecked")
public List<Party> queryPartiesBetweenDates(Date startDate, Date endDate, String sortBy, Integer count) {
    Criteria criteria = getCurrentSession().createCriteria(Party.class);
    if (startDate != null) {
        criteria.add(Restrictions.ge("startDate", startDate));
    }
    if (endDate != null) {
        criteria.add(Restrictions.lt("endDate", endDate));
    }
    if (count != null) {
        criteria.setMaxResults(count);
    }
    if (sortBy == null || !sortBy.equals("distance")) {
        criteria.addOrder(Order.asc("startDate"));
    }
    return criteria.list();
}

谢谢!

CriteriaBuilder 比原生的 hibernate Restriction API 更冗长,主要原因是当您使用 MetaModel 时它是完全类型化的,这意味着如果类型或导致查询无效的列的名称。 下面是一个不使用生成的 MetaModel 类 的示例,主要类似于旧的 Hibernate 代码。

EntityManager em = emf.createEntityManager(); // or injected

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Party> query = cb.createQuery(Party.class);
Root<Party> partyRoot = query.from(Party.class);
query.select(partyRoot);

Predicate predicate = null;
Path<Date> startDatePath = partyRoot.<Date>get("startDate");
if (startDate != null) {
    predicate = cb.greaterThanOrEqualTo(startDatePath, startDate);
}
if (endDate != null) {
    Predicate additionalPredicate = cb.lessThanOrEqualTo(partyRoot.<Date>get("endDate"), startDate);
    if (predicate == null) {
        predicate = additionalPredicate;
    } else {
        predicate = cb.and(predicate, additionalPredicate);
    }
}
query.where(predicate);

if (sortBy == null || !sortBy.equals("distance")) {
    query.orderBy(cb.asc(startDatePath));
}

return em.createQuery(query).setMaxResults(count).getResultList();

如果您有很多谓词,将它们添加到列表或创建一个实用方法来处理它们可能是个好主意。