Listening for proxy replacement

Sorry for using the wrong words in the topic title, what I want to do is get notified

   a) when a proxy is created instead of fetching an entity from the database
   b) when the proxy is replaced with the entity it represents

The purpose is to log how long each proxy lives, as we suspect some of our lazy associations are fetched straight away. Ideally, it would be similar to EventListener, say onProxyCreation(Object proxy, Class entityClass, Serializable id) and onProxyReplacement(Object proxy, Object entity, Serializable id).
We could then use this to log a warning when a proxy lives for less than eg 100ms.

We are currently using Hibernate 5.6 without JPA (ie using Session interface).

I think you could try to achieve that by implement a custom ProxyFactory which you can provide yourself through a Hibernate service by registering a org.hibernate.bytecode.spi.ProxyFactoryFactory. See org.hibernate.bytecode.internal.bytebuddy.ProxyFactoryFactoryImpl for an example. I guess you’ mostly copy the existing bytebuddy implementation and just add the aspects you care about to the respective methods getProxy and org.hibernate.proxy.LazyInitializer#getImplementation().

1 Like