Saturday, December 13, 2008

Hibernate: Using proxies when classes have final methods

If you use Hibernate, then you have probably encountered proxies. Hibernate generates and returns proxies for entities when (a) Hibernate knows the primary key of the entity, (b) it's not necessary to actually retrieve the entity from the database right away, and (c) the entity class is proxyable. Entities accessed through the Session.load method and through lazy references from other classes are all eligible to be proxied.

The Hibernate documentation states: "... you may not use a CGLIB proxy for a final class or a class with any final methods." But this statement seems a little doubtful, since every Java class has final methods, because Object itself has final methods. Obviously Hibernate and CGLIB are able to create proxies for classes with at least some final methods. But maybe CGLIB has special handling for the final methods of Object?

Actually its seems that classes with any number of final methods can be proxied. However, CGLIB cannot override the final methods in the proxy, so those methods may not work very well, and calling them will not initialize the proxy. But if the methods do not depend on any fields of the class, then they will probably be okay. (Fields defined in the entity class will be present in the proxy but, except for the ID field or fields, will not be initialized.)

0 Comments:

Post a Comment

<< Home