0

I am using Spring Boot for building Microservice. I created entity objects with @OneToMany and @ManyToOne relationships like below,

class parent {
   @OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="parentEntity")
   List<Child> childEntity;
   ...
}

class child {
   @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
   @JoinColumns({...})
   Parent parentEntity;
   ...
}

In Child Repository class I have written a JPQL to fetch data from DB.

In DB there are close to 400 records. The issue I see is on performance side. It executes the query first and I see below lines in logs for 400 records,

[org.hibernate.Loader.loader][debugf][Result set row:0]
[org.hibernate.Loader.loader][getRow][Result row: EntityKey[com.Child#component[...]]

Above lines are getting executed for 400 records and then

[org.hibernate.engine.internal.TwoPhaseLoad][initializeEntityEntryLoadedState]
 [Processing Attribute `column1`: value='1']
 [Attribute (`column1`) - enhanced for Lazy Loading? - false]

I have 4 columns in child table. So above lines are getting repeated for 4 * 400 records and overall I see it takes close to 2 seconds for this transaction.

Is there a way I can optimize this? I don't do any business logic. Is this is how is expected?

halfer
  • 19,824
  • 17
  • 99
  • 186
Lolly
  • 34,250
  • 42
  • 115
  • 150
  • Try removing LAZY fetch type from your parent class for your child entity and see if that makes a difference. Just as a side note, if exposing via an API, make sure you take care of your circular dependency. – Dhiren Dash Jan 30 '22 at 20:02
  • This is problem `N+1 selects` [https://stackoverflow.com/questions/32453989/what-is-the-solution-for-the-n1-issue-in-jpa-and-hibernate](https://stackoverflow.com/questions/32453989/what-is-the-solution-for-the-n1-issue-in-jpa-and-hibernate) – Konanaw Jan 30 '22 at 21:27

0 Answers0