java—entitygraph和typedquery同时使用

lfapxunr  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(379)

我尝试同时使用两个hibernate功能: EntityGraph 和标准api TypedQuery 但无法解决如何将它们结合使用:

@Override
public List<Customer> findByFilterEntityGraph(final CustomerFilter filter) {
    final EntityManager entityManager = sessionFactory.createEntityManager();
    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Customer> criteriaQuery = criteriaBuilder.createQuery(Customer.class);
    final Root<Customer> customerMetamodel = criteriaQuery.from(Customer.class);
    final Predicate name = criteriaBuilder.like(customerMetamodel.get("name"), filter.getName());
    final Predicate age = criteriaBuilder.between(
            customerMetamodel.get("age"), filter.getAgeFrom(), filter.getAgeTo());
    final Predicate predicate = criteriaBuilder.and(name, age);
    criteriaQuery.where(predicate);

    final TypedQuery<Customer> query = entityManager.createQuery(criteriaQuery);
    final EntityGraph<?> entityGraph = entityManager.getEntityGraph("customer.products");
    Map<String, Object> properties = Map.of("javax.persistence.fetchgraph", entityGraph);

    // ... ?
    return null;
}

我相信我的朋友 EntityGraph 申报正确,因为它是在其他地方工作。但我不知道如何使用它们。
我知道这样的方法:

public Optional<Customer> findByIdEntityGraph(final long customerId) {
    final EntityManager entityManager = sessionFactory.createEntityManager();
    final EntityGraph<?> entityGraph = entityManager.getEntityGraph("customer.products");
    Map<String, Object> properties = Map.of("javax.persistence.fetchgraph", entityGraph);
    final Customer customer = entityManager.find(Customer.class, customerId, properties);
    return Optional.ofNullable(customer);
}

允许将标准api与 EntityGraph 但对于单一结果和无条件的情况,如带 TypedQuery .
可以使用 EntityGraph 以及 TypedQuery 一起列清单?

ma8fv8wu

ma8fv8wu1#

是的,这是允许的。我认为您只是错误地使用了fetch图,而应该使用load图:https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs001.htm

相关问题