Java – use kotlin’s Hibernate: @ manytoone (fetch = fetchtype. Lazy)

I'm using hibernate and kotlin, and I met fetchtype on the @ manytoone relationship Lazy problem Consider the following:

@ManyToOne(fetch = FetchType.LAZY)
open var event: Event?

The problem is when using fetchtype When lazy, the obtained event will be class event _$$_ jvst _… And with javaassistlazyinitializer But the event will never be initialized and everything will be null or empty

>Delete fetchtype After lazy, everything is normal. > This does not happen in Java. > I try to add open to var so that I can proxy events correctly No effect. > Of course, all @ entity courses are open If the open keyword is deleted, no proxy will be created, so there will be no laziness

My guess is that hibernate cannot easily proxy these default kotlin getters Is there a solution?

Solution

You can use this static method to deproxy your entity

/**
 * Utility method that tries to properly initialize the Hibernate cglib
 * proxy.
 * @param <T>
 * @param maybeProxy -- the possible Hibernate generated proxy
 * @param baseClass -- the resulting class to be cast to.
 * @return the object of a class <T>
 * @throws ClassCastException
 */
public static <T> T deproxy(Object maybeProxy,Class<T> baseClass) throws ClassCastException {
    if (maybeProxy instanceof HibernateProxy) {
        return baseClass.cast(((HibernateProxy) maybeProxy).getHibernateLazyInitializer().getImplementation());
    }
    return baseClass.cast(maybeProxy);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>