Search code examples
javahibernatejpacglib

How does CGLIB proxy String or other final classes?


I would like to ask a question regarding Lazy Fetching in Hibernate.

As far as I know, in order to implement Lazy Fetching, Hibernate creates a placeholder that is a proxy of the real property.

What if my entity includes a String property or other final class? How will CGLIB subclass it?


Solution

  • Telling the long story short:

    1. CGLib cannot proxy final classes at all, you might have seen previously in your logs something like Could not generate CGLIB subclass of class [class SomeClass]: Common causes of this problem include using a final class or a non-visible class
    2. Hibernate proxies your entity class at first, having corresponding attribute Interceptors injected into respective getters, so that actual call stack usually looks like the following:
    myEntity.getMyString()
       |_ proxy.getMyString()
         |_ lazyAttributeLoadingInterceptor.fetchAttribute(myEntity,"myString")
           |_ ... (actual call to underlying DB if required)
    

    That is, everything you state here is correct:

    Hibernate creates a placeholder that is a proxy of the real ...

    if you end this phrase with the word entity/pojo instead of property