我尝试同时使用两个Hibernate功能:EntityGraph
和Criteria APITypedQuery
,但无法解决如何将它们一起使用:
@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);
}
允许将Criteria API与EntityGraph
一起使用,但对于单个结果,并且不使用条件,如与TypedQuery
一起使用过滤器。
是否可以将EntityGraph
和TypedQuery
一起用于列表?
是允许的。我认为您只是错误地使用了提取图,而您应该使用负载图:https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs001.htm