4 Mayıs 2023 Perşembe

@Batch Anotasyonu

Giriş
JPQL ile gelen LEFT JOIN FETCH kullanmak istemiyorsak @Batch kullanılabilir

Örnek
Şöyle yaparız.
@Entity
public class Doctor {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;

  @OneToMany(mappedBy = "doctor", fetch = FetchType.LAZY)
  @org.hibernate.annotations.BatchSize(size = 5)
  private Collection<Appointment> appointments;
}
Açıklaması şöyle. Tek bir Doctor nesnesi çeksek bile biraz daha fazla veri çekiyor. Aslında bu bence kötü bir çözüm.
Whenever Hibernate initializes one Doctor – Appointments collection it will also initialize Appointments for four more Doctors. The query which Hibernate generates is as follows.

SELECT appointmen0_.doctor_id,
 appointmen0_.id,
 appointmen0_.id, 
 appointmen0_.appointmentTime, 
 appointmen0_.doctor_id 
FROM Appointment 
 WHERE appointmen0_.doctor_id IN (?, ?, ?, ?, ?)

In our example of 10 doctors, a ceiling of N + 1 / @BatchSize, which is 10 + 1 / 5 = 3 total queries will be executed to fetch Doctors and all the Appointments. It’s not really a great optimization as still more queries are executed than we would like, but it is some improvement.

Please also bear in mind that it’s a global optimization. Once this annotation is present, referring to one of our Doctor’s appointments will result preloading Appointments for another four Doctors.