I’m facing N+1 problem and want to fix it using only Static defition (fetch = FetchType.?, @Fetch(FetchMode.?) and @BatchSize):
Entities:
@Entity
@Table(name = "persons")
@BatchSize(size = 20)
@NoArgsConstructor @AllArgsConstructor
@Getter @Setter
@ToString
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne(mappedBy = "person")
@Fetch(FetchMode.JOIN)
private PersonDetails personDetails;
}
@Entity
@Table(name = "person_details")
@BatchSize(size = 20)
@NoArgsConstructor @AllArgsConstructor
@Getter @Setter
@ToString
public class PersonDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne
@JoinColumn(name = "person_id")
private Person person;
}
Fetching:
try (var em = emf.createEntityManager()) {
em.getTransaction().begin();
var persons = em.createQuery("FROM Person", Person.class).getResultList();
System.out.println(persons); // 4 persons found
em.getTransaction().commit();
}
Console output:
Hibernate: select p1_0.id from persons p1_0
(and the next query is repeated 4 times (due to “N+1” behavior)):
Hibernate: select pd1_0.id,p1_0.id from person_details pd1_0 left join persons p1_0 on p1_0.id=pd1_0.person_id where pd1_0.person_id=?
I know that “N+1” can be fixed with “FROM Person p JOIN FETCH p.personDetails” or with Entity Graphs.
But my goal is to understand - can this be fixed with Static definition (fetch = FetchType.?, @Fetch(FetchMode.?) and @BatchSize)
P.S. Why @BatchSize (at the class level) doesn’t help here?
P.S. Hibernate version is “6.6.5.Final”