Is it a problem to access a Hibernate entity getter in a for loop?


#1

Hi all,

what is my problem? We got some performance issues with a statement and i don’t know why. The following Statement we do use:

for (Address  address : employee.getAddreses()) {
				// do something...
}

The call employee.getAddresses loads data into the employee object. is it ok to use this Statement within a for Loop? or does it cause Performance issues? And why?

Another alternative Approach would be:

List<Address> addresses = employee.getAddresses(); <-- hibernate call outside of foor loop
for (Address : addressess) {
    // do something...
}

Regards
DonMallo


#2

We got some performance issues with a statement and I don’t know why.

First of all, you only mentioned you have a performance problem but did not explain what exactly does the performance problem consist of.

If inside the for-loop you are accessing some lazy associations of the Address entity, then you might have bumped into a N+1 query issue which can be easily fixed using a JOIN FETCH directive.

The call employee.getAddresses loads data into the employee object. is it ok to use this Statement within a for Loop? or does it cause Performance issues? And why?

List addresses = employee.getAddresses(); <-- hibernate call outside of foor loop
for (Address : addressess) {
    // do something…
}

There is no difference. The foreach loop calls the right-hand argument only once at the beginning of the loop, so there will be a single employee.getAddresses() call.

Whenever you have a performance issue in your data access layer, the first thing you need to do is to check the SQL query log and see what statements are executed.

Check out this article about the best way to log SQL statements with JDBC, JPA or Hibernate.


#3

Hi vlad,

thanks for answer. thats what i assumed… we have some performance issues and i’m trying to identify them. i am not a hibernate pro.

over all, it was a core java question, hehe. :grin:

i checked the SQL, it looks qiute good (it does what i want it to do). no N+1 query issue.
I was a little bit unsure about the hibernate call in the for loop, but as you said, it should be the same.
I think, i have to dive a little deeper in the code/configuration.

thanks
Don


#4

That’s right.

If you have performance problems, it’s best to start getting an insight into what the underlying framework does. And SQL statement logging is the best place to start.

Analyzing the logs will tell you:

  • If you have more SQL statements than necessary, either for reading data (e.g. N+1) or for writing it, in which case you might need batching or bulk operations
  • If the auto-generated SQL statements are efficient
  • If there’s a possibility to add a database index to speed up reads

Check out these 14 high-performance Java Persistence tips for more details about what you need to be aware of when you have performance issues in your data acess layer.