Hibernate with Kotlin: @ManyToOne(fetch = FetchType.LAZY)

Viewed 1966

I am using Hibernate with Kotlin and I am having an issue with FetchType.LAZY on @ManyToOne relations. Consider following:

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

The problem is that when FetchType.LAZY is used, the fetched Event will be of class Event_$$_jvst_... with JavaassistLazyInitializer on it. But the event will never be initialized, everything will be null or empty.

  1. Once the FetchType.LAZY is removed, everything works correctly.
  2. This didn't happen in Java.
  3. I tried to add open on the var so that the Event can be correctly proxied. No effect.
  4. All the @Entity classes are of course open as well. If the open keyword is removed, there will be no proxy created and so no laziness.

My guess is that Hibernate cannot easily proxy these default kotlin getters. Is there a way to solve it?

2 Answers

you could 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);
}
Related