0

I found some solutions to avoid N+1 problem but this solutions works only for single Many-To-One relationship.

For example, the following question: What is the solution for the N+1 issue in JPA and Hibernate?

The problem that I'm trying to solve is this:

@Entity 
public class Book implements Serializable { 
    
  @Id 
  private Long id; 

  private String title; 
    
  @ManyToOne(fetch = FetchType.LAZY) 
  private Author author; 

  @ManyToOne(fetch = FetchType.LAZY) 
  private Brand brand;
}

Solutions like try to fetch through JPQL doesn't work and fetch just one relationship, for example:

SELECT b FROM Book b 
INNER JOIN FETCH b.author 
INNER JOIN FETCH b.brand

In this case, only 'author' relationship would be fetched and N+1 problem will happen with 'brand' relationship.

Do you know any solution to solve this specific problem?

Thank you!

1 Answers1

0

Try this with criteria api:

CritieriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Book> cq = cb.createQuery(Book.class);

Root<Book> root = cq.from(Book.class);
root.fetch("author"); //root.fetch(Book_.author) if use metamodel
root.fetch("brand"); //root.fetch(Book_.brand) if use metamodel

cq.select(root);

List<Book> result = entityManager.createQuery(cq).getResultList();
JLazar0
  • 1,257
  • 1
  • 11
  • 22