Search code examples
spring-boothibernatejpaormhibernate-mapping

@Batchsize annotation not working for OneToMany


I have following classes and on annotating @BatchSize annotation it is not working and I am getting n+1 select query.

Class Shipment{
 @OneToMany(fetch = FetchType.LAZY, mappedBy = order.shipment, cascade = CascadeType.ALL, 
 orphanRemoval = true)
 @BatchSize(size=20)
 Set<Orders> orders = new Hashset(); <---- Batch size annotation not working 
 }

Order.class

class Order{
 @ToString.Exclude
 @ManyToOne
 @JoinColumn(name = "item_fk")
 Item item;

 @ToString.Exclude
 @ManyToOne
 @JoinColumn(name = "shipment_fk")
 Shipment shipment; }

Item.class

class Item{
 String id;
 String name;
}

What is mistake in implementation that i am getting n+1 queries?


Solution

    1. Try to use List<Orders> instead of Set<Orders>.

    2. Please note as it's mentioned in the documentation:

    However, although @BatchSize is better than running into an N+1 query issue, most of the time, a DTO projection or a JOIN FETCH is a much better alternative since it allows you to fetch all the required data with a single query.