2

I have written an interceptor to log onLoad events, but I would like to be able to differentiate loads from fetches--namely, whether Hibernate had to fetch the entity from the database, or if it simply loaded it from one of its caches.

The reason I can't use Hibernate statistics is because I would like a more fine-grained analysis of what method is causing which load/fetch/query, which is why I am using an interceptor. So I guess my question is, how can I differentiate loads from fetches using an interceptor?

Thanks in advance!

user2993589
  • 81
  • 1
  • 5

2 Answers2

2

After a lot of poking around, what I am actually looking for is loadFromDatasource in DefaultLoadEventListener. Hibernate will use event.isAssociationFetch() to see if it should log it as a fetch in its statistics. Overriding this method and adding that check will mirror Hibernate Statistics exactly.

I was able to track this down via this: In hibernate statistics whats the difference between load and fetch, and registered event listeners with this: eventlisteners using hibernate 4.0 with spring 3.1.0.release?

However, one thing I noticed is that you will want to clear the Event Listener Group, or else there will be their default listener, which will fetch the object, and when your listener checks, it will think the object has already been fetched (which it has), and thus not log it in your statistics.

Community
  • 1
  • 1
user2993589
  • 81
  • 1
  • 5
0

Instead of having an interceptor you can try extending the DefaultPostLoadEventListener.

The event system gives you more control over entity state change events.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • I'm a little confused by the API for this--does this only get called when Hibernate has to fetch an entity from the database, or is this called after every entity load? – user2993589 May 29 '14 at 22:09
  • Better to give it a try and see when it gets called. – Vlad Mihalcea May 30 '14 at 02:56
  • It looks like postLoad is getting called every time an entity is loaded, which is not what I want. To test this, I put in an atomic counter and compared it to Hibernate's statistics. The number it shows is exactly equal to the number of Entity Loads, but is not the same as the number of Entity Fetches. Do you know of a way to listen _only_ for fetch events? – user2993589 May 30 '14 at 17:32
  • I don't know if there is such event. – Vlad Mihalcea May 30 '14 at 17:36
  • Ah--that is unfortunate. How does Hibernate Statistics track that, then? – user2993589 May 30 '14 at 18:04
  • I was able to find what I was looking for, but your help definitely pointed me in the right direction. Thanks! – user2993589 May 30 '14 at 20:59
  • Please post your final solution so others can find it too. – Vlad Mihalcea May 31 '14 at 03:44