4 Replies Latest reply on Apr 10, 2011 8:54 PM by vgarmash

    hibernate proxy and typecast

    porcherg

      With Hibernate, a proxy is used for lazy associations. The real object is only fetched from the database when accessed. But for polymorphic association, the proxy is a subclass of the top level class. Any call to "instanceof" or isAssignableFrom... does not work.

      This is an issue for example in WireContext, because we check if a descriptor is an instance of Initializable during it's construction.

      In this post http://www.mail-archive.com/hibernate-devel@lists.sourceforge.net/msg02307.html, it is said that a solution is to use outer-join fetching (= disabling lazy loading) or to explicitly load the object from the session.

      Is there any other solution for this issue ?

      regards,
      Guillaume

        • 1. Re: hibernate proxy and typecast
          tom.baeyens

          another potential solution to this problem is to use polymorfic methods on the object.

          i believe that is the only solution that will really work.

          for WireContext and Initializable, you could e.g. introduce a method isInitializable on the Descriptor or AbstractDescriptor

          • 2. Re: hibernate proxy and typecast
            porcherg

             

            "tom.baeyens@jboss.com" wrote:
            another potential solution to this problem is to use polymorfic methods on the object.

            i believe that is the only solution that will really work.

            for WireContext and Initializable, you could e.g. introduce a method isInitializable on the Descriptor or AbstractDescriptor


            The method isInitializable can be used to check if the object is an instance of Initializable, but the cast still fails.
            In the WireContext, there 's a list of pendingInitialization. A pending init has a Initializable.

            To remove the cast, we need to change pendingInitialization to use only AbstractDescriptor, and to add an empty "initialize" method in AbstractDescriptor.

            With the change, the tests pass. Is this a good way to resolve this issue ?

            Guillaume

            • 3. Re: hibernate proxy and typecast
              tom.baeyens

              i merged initializable into descriptor.

              initializable disappeared and the methods were added to descriptor.

              • 4. Re: hibernate proxy and typecast
                vgarmash

                Yes - you need ProxyVisitorPattern: http://community.jboss.org/wiki/ProxyVisitorPattern because lazy polymorphic are proxies and not your types.

                 

                Other solution: split you entity class to interface and implementation so then in mapping subclasses you can specify the interface name in proxy attribute. See

                5.1.17. Subclass in hibernate reference.