user130532
user130532

Reputation:

Should I be using hibernate 2nd level caching?

I have a domain object that has a particular state that upon a certain event handled by a service object, I need to examine all instances that match that state. This event can occur fairly frequently so doing a hibernate query every time would be inefficient. So I have a collection of these that I store at startup and maintain whenever needed.

My question is, if I configured hibernates second level cache, would I be able to make the following change to my code without being concerned about performance?

from:

public void handleEvent(SomeEvent someEvent) {
    for (Entity entity : matchedEntitiesSet) {
         // evaluate each entity for required changes. update state as needed
         // persist any changes
    }

    // update my collection with the current repository result.
}

to:

public void handleEvent(SomeEvent someEvent) {
    for (Entity entity : dao.getSomeEventsByCriteria(criteria)) {
         // evaluate each entity for required changes. update state as needed
         // persist any changes
    }
}

Effectively I would change to use the DAO exclusively as opposed to maintaining a set of said matched entities within my service.

Upvotes: 4

Views: 146

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128749

Yes, that's exactly what the second-level cache/query cache is for. Hibernate will handle it more consistently and effectively than you will. Your profiler will help you tune the cache to meet your parameters. You did profile the app before you tried to optimize it, right?

Upvotes: 1

WebThinker
WebThinker

Reputation: 181

Looks like if you enable query cache and second level cache then it should work fine. http://www.javalobby.org/java/forums/t48846.html

Upvotes: 0

Related Questions