Hibernate generates m + 1 request in many cases

My problem is very simple, but I don’t know how to make Hibernate the way I want: - MainTable table has many-2-One with ParentTable (with 100 rows). MainTable points to m = 26 lines of 100 lines in ParentTable

@ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "PARENT_ID") @Fetch(FetchMode.JOIN) 

When I just request "from MainTable"

it will generate 26 + 1 queries

When I track requests, the first request only loads PARENT_ID, using 26 subsequent requests. I guess it should have a way to load the whole PARENT_TABLE into the 1st query.

Please help by suggesting that:

  • FetchType.EAGER is MUST
  • Using from MainTable mt left join fetch mt.parent parent is fine, but we have a lot of associations
+6
source share
1 answer
  // Annotate ParentTable Persistance class file with a batch Size @BatchSize(size=100) class ParentTable{ .. } 

 @ManyToOne @JoinColumn(name = "PARENT_ID") 

This will reduce the number of requests by n / 100 + 1.

The reason for this problem is that sleep mode will retrieve data in lazy mode from the inside (I'm not talking about FetchMode.Lazy ). Lazy mode can be excluded using FetchMode.SUBSELECT , which is applicable only to collections. When it comes to @ManyToOne , you can select batch data by specifying batchSize .

Fetch Launcher Summary

FetchMode.SUBSELECT

One query for parent, one query for linked table. Applicable only to collection structure. Only 2 requests completed.

FetchMode.SELECT

One request for parent, N requests for child.

FetchMode.JOIN

One query for the parent, N queries for the child, but the database search is first in the JOIN.

FetchType.Batch

One request for parent and n / batchSize + 1 requests.


There are two types of fetch based on when queries should be executed.

FetchType.EAGER :

Requests are launched instantly.

FetchType.LAZY :

Queries are triggered when a child is accessed. Thus, the number of executed requests will depend on the number of access child objects.

The principles behind Fetch strategies are better explained here .

+3
source

Source: https://habr.com/ru/post/922305/


All Articles