Estou tentando utilizar a Example API para fazer uma pesquisa com filtros dinâmicos. Para isso, criei o Repository da seguinte forma:
public interface OrderRepository extends CrudRepository<Order, Long>, QueryByExampleExecutor<Order> {
}
Meu service chama a consulta pelo filtro dinâmico da seguinte forma:
public List<Order> list(Long consumerId) {
Order order = new Order();
order.setConsumerId(consumerId);
Iterable<Order> ordersIt = orderRepository.findAll(Example.of(order));
return StreamSupport.stream(ordersIt.spliterator(), false).collect(Collectors.toList());
}
A consulta funciona com sucesso filtrando pela order que eu informo. Porém, está ocorrendo o problema de N+1 consultas que é possível visualizar no log:
select order0_.id as id1_3_, order0_.consumer_id as consumer2_3_, order0_.restaurant_id as restaura3_3_ from orders order0_ where order0_.consumer_id=2
select restaurant0_.id as id1_5_0_, restaurant0_.city as city2_5_0_, restaurant0_.state as state3_5_0_, restaurant0_.street1 as street4_5_0_, restaurant0_.street2 as street5_5_0_, restaurant0_.zip as zip6_5_0_, restaurant0_.name as name7_5_0_ from restaurants restaurant0_ where restaurant0_.id=?
A consulta deveria ter feito join com o restaurant, mas isso não ocorreu. Se eu criar o método no Repository sem a Example API adicionando o @EntityGraph, consigo fazer o Fetch e consequentemente é feito o join na consulta:
@EntityGraph(attributePaths = { "restaurant" }, type = EntityGraphType.FETCH)
List<Order> findByConsumerId(Long consumerId);
select order0_.id as id1_3_0_, restaurant1_.id as id1_5_1_, order0_.consumer_id as consumer2_3_0_, order0_.restaurant_id as restaura3_3_0_, restaurant1_.city as city2_5_1_, restaurant1_.state as state3_5_1_, restaurant1_.street1 as street4_5_1_, restaurant1_.street2 as street5_5_1_, restaurant1_.zip as zip6_5_1_, restaurant1_.name as name7_5_1_ from orders order0_ left outer join restaurants restaurant1_ on order0_.restaurant_id=restaurant1_.id where order0_.consumer_id=?
O problema é que não consigo usar o @EntityGraph com a Example API pois eu teria que implementar o método na interface e quando chamasse o findAll a anotação não seria repassada. Tentei dessa forma, mas não foi feito o join:
@EntityGraph(attributePaths = { "restaurant" }, type = EntityGraphType.FETCH)
default Iterable<Order> findAllByFilter(Example<Order> example) {
return findAll(example);
}
Como fazer a Example API funcionar sem o problema de performance das consultas N+1?
Minhas entidades:
@Entity
@Table(name = "orders")
@DynamicUpdate
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long consumerId;
@ManyToOne
private Restaurant restaurant;
}
@Entity
@Table(name = "restaurants")
@DynamicUpdate
public class Restaurant {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}