How to convert a Hibernate proxy to a real entity object

后端 未结 10 709
离开以前
离开以前 2020-11-22 16:49

During a Hibernate Session, I am loading some objects and some of them are loaded as proxies due to lazy loading. It\'s all OK and I don\'t want to turn lazy lo

10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 17:47

    I found a solution to deproxy a class using standard Java and JPA API. Tested with hibernate, but does not require hibernate as a dependency and should work with all JPA providers.

    Onle one requirement - its necessary to modify parent class (Address) and add a simple helper method.

    General idea: add helper method to parent class which returns itself. when method called on proxy, it will forward the call to real instance and return this real instance.

    Implementation is a little bit more complex, as hibernate recognizes that proxied class returns itself and still returns proxy instead of real instance. Workaround is to wrap returned instance into a simple wrapper class, which has different class type than the real instance.

    In code:

    class Address {
       public AddressWrapper getWrappedSelf() {
           return new AddressWrapper(this);
       }
    ...
    }
    
    class AddressWrapper {
        private Address wrappedAddress;
    ...
    }
    

    To cast Address proxy to real subclass, use following:

    Address address = dao.getSomeAddress(...);
    Address deproxiedAddress = address.getWrappedSelf().getWrappedAddress();
    if (deproxiedAddress instanceof WorkAddress) {
    WorkAddress workAddress = (WorkAddress)deproxiedAddress;
    }
    

提交回复
热议问题