kiedysktos
kiedysktos

Reputation: 4100

Spring JPA caching - should I avoid retrieving the same resource from repository a few times?

I have a following line in my code:

String productName = Utils.getProductName(productId, productRepository, language);

This util method retrieves the product using method findOne(productId), but has some additional logic well. It is used in multiple places in my code.

In one place, a few lines lower, I need the Product object, so I do following:

Product product = productRepository.findOne(productId);

Here I retrieve the Product again, so we have the same action on the database again. But I believe that JPA (Hibernate) caches the object so I don't have to worry about it, the performance won't be affected. Am I right?

Of course, I try to avoid such a duplicity. But in this case refactoring getProductName method would have an impact on other places where I use this method. So I'd like to just leave it as it is. But if the performance cost would be noticeable, I'd better tweak the code.

Upvotes: 0

Views: 2317

Answers (1)

user3805841
user3805841

Reputation: 34

Yes, there is a first level cache enabled on the entity manager. "In first level cache CRUD operations are performed per transaction basis to reduce the number of queries fired to the database."

http://www.developer.com/java/using-second-level-caching-in-a-jpa-application.html

Just be sure not to create "inconsistent" states without informing the entity manager or flush the changes to the DB.

Upvotes: 1

Related Questions