Hibernate中使用ByteBuddy代理的MethodHandler陷入无限循环 [英] MethodHandler in Hibernate using ByteBuddy proxies gets stuck in endless loop

查看:66
本文介绍了Hibernate中使用ByteBuddy代理的MethodHandler陷入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为Hibernate迁移一个旧工具,以基于实体统计信息自动进行预取.旧工具使用了Hibernate 3.1,因此需要完成一些工作.传统上,Hibernate使用CGlib代理,但是当我在开发最新版本的Hibernate时,我正在将代理生成更改为ByteBuddy.

I'm currently migrating an old tool for Hibernate to automate prefetching based on entity statistics. The old tool used Hibernate 3.1, so there's some job to be done. Traditionally, Hibernate used CGlib proxies, but as I'm developing for the latest release of Hibernate I am changing the proxy generation to ByteBuddy.

但是,自从更改为ByteBuddy以来,我在使MethodHandler正常工作时遇到了一些问题.我工具中的methodhandler应该可以处理对代理的所有调用,以收集必要的统计信息.目前,我的方法处理程序如下所示:

However, since the change to ByteBuddy I've been having some problems with getting the MethodHandler to work. The methodhandler in my tool is supposed to handle all the calls to the proxies to enable the gathering of necessary statistics. Currently, my method handler looks like this:

public class EntityProxyMethodHandler implements ProxyConfiguration.Interceptor, Serializable {

private final EntityTracker entityTracker;
private final Object proxiedObject;
private final String proxiedClassName;

EntityProxyMethodHandler(
        Object proxiedObject,
        String proxiedClassName,
        Set<Property> persistentProperties,
        ExtentManager extentManager) {
    this.proxiedObject = proxiedObject;
    this.proxiedClassName = proxiedClassName;
    this.entityTracker = new EntityTracker(persistentProperties, extentManager );
}

@Override
@RuntimeType
public Object intercept(@This Object instance, @Origin Method method, @AllArguments Object[] arguments)
        throws Exception {
    final String methodName = method.getName();
    if ( "toString".equals( methodName ) ) {
        return proxiedClassName + "@" + System.identityHashCode( instance );
    }
    else if ( "equals".equals( methodName ) ) {
        return proxiedObject == instance;
    }
    else if ( "hashCode".equals( methodName ) ) {
        return System.identityHashCode( instance );
    }
    else if ( arguments.length == 0 ) {
        switch ( methodName ) {
            case "disableTracking": {
                boolean oldValue = entityTracker.isTracking();
                entityTracker.setTracking( false );
                return oldValue;
            }
            case "enableTracking": {
                boolean oldValue = entityTracker.isTracking();
                entityTracker.setTracking( true );
                return oldValue;
            }
            case "isAccessed":
                return entityTracker.isAccessed();

            default:
                break;
        }
    }
    else if ( arguments.length == 1 ) {
        if ( methodName.equals( "addTracker" ) && method.getParameterTypes()[0].equals( Statistics.class ) ) {
            entityTracker.addTracker( (Statistics) arguments[0] );
            return null;
        }
        else if ( methodName.equals( "addTrackers" ) && method.getParameterTypes()[0].equals( Set.class ) ) {
            @SuppressWarnings("unchecked")
            Set<Statistics> newTrackers = (Set) arguments[0];
            entityTracker.addTrackers( newTrackers );
            return null;
        }
        else if ( methodName
                .equals( "extendProfile" ) && method.getParameterTypes()[0].equals( Statistics.class ) ) {
            entityTracker.extendProfile( (Statistics) arguments[0], instance );
            return null;
        }
        else if ( methodName
                .equals( "removeTracker" ) && method.getParameterTypes()[0].equals( Statistics.class ) ) {
            entityTracker.removeTracker( (Statistics) arguments[0] );
            return null;
        }
    }
    entityTracker.trackAccess( instance );
    return method.invoke( instance, arguments ); // Gets stuck here, the method interception gets intercepted endlessly
}

代理工厂如下:

public class EntityProxyFactory {
private static SessionFactoryImplementor sessionFactory = AutofetchIntegrator.getSessionFactory();
private static final ConcurrentMap<Class<?>, Constructor<?>> entityConstructorMap = new ConcurrentHashMap<>();

private static <T> Constructor<T> getDefaultConstructor(Class<T> clazz) throws NoSuchMethodException {
    Constructor<T> constructor = clazz.getDeclaredConstructor();
    if ( !constructor.isAccessible() ) {
        constructor.setAccessible( true );
    }

    return constructor;
}

static Object getProxyInstance(
        Class persistentClass,
        Set<Property> persistentProperties,
        ExtentManager extentManager)
        throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {

    if ( Modifier.isFinal( persistentClass.getModifiers() ) ) {
        // Use the default constructor, because final classes cannot be inherited.
        return useDefaultConstructor( persistentClass );
    }
    final ProxyConfiguration proxy = (ProxyConfiguration) Environment.getBytecodeProvider()
            .getProxyFactoryFactory()
            .buildBasicProxyFactory( persistentClass, new Class[] { TrackableEntity.class } )
            .getProxy();
    proxy.$$_hibernate_set_interceptor( new EntityProxyMethodHandler(proxy,persistentClass.getName(),
            persistentProperties,
            extentManager
    ) );
    return proxy;
}

private static Object useDefaultConstructor(Class<?> clazz)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    if ( !entityConstructorMap.containsKey( clazz ) ) {
        entityConstructorMap.put( clazz, getDefaultConstructor( clazz ) );
    }

    final Constructor<?> c = entityConstructorMap.get( clazz );
    return c.newInstance();
}

}

当我运行包含访问代理字段之一的测试时,我得到了以下内容的无尽调用堆栈:

When I run a test containing accessing one of the fields of the proxies, I get an endless callstack of the following:

EntityProxyMethodHandler.intercept(EntityProxyMethodHandler.java:105)
Employee.$HibernateBasicProxy$Rbz7NDpP.getSupervisor(Unknown Source)

Caused by java.lang.reflect.InvocationTargetException:
EntityProxyMethodHandler.intercept(EntityProxyMethodHandler.java:105)
Employee.$HibernateBasicProxy$Rbz7NDpP.getSupervisor(Unknown Source)

由于某种原因,它不调用真实实体,而是调用代理本身,陷入无尽的拦截循环中.我不知道如何解决这个问题,我试图找到一种在方法处理程序中调用目标"的方法,但由于某种原因,由于某种原因,代理工厂生成的代理未实现 HibernateProxy -接口.也许这是ByteBuddy有一些方法可以解决的问题,但是由于我对框架没有足够的经验,所以我还没有找到解决方法.

For some reason, it does not call the real entity, but the proxy itself, getting stuck in an endless loop of intercepts. I have no idea how to resolve this, I've tried finding a way to call the "target" inside the method handler, but couldn't find anything since for some reason the proxies generated by the proxy factory is not implementing the HibernateProxy-interface. Maybe this is a problem that ByteBuddy has some ways to deal with, however since I'm rather inexperienced with the framework I haven't found a way yet.

此外,在我改用Javassist-proxies之前,此方法也可以正常工作.然后我有类似的课程:

Also, this was working flawlessly before when I used Javassist-proxies instead. Then I had similar classes:

public class EntityProxyFactory {

private static final CoreMessageLogger LOG = CoreLogging.messageLogger(AutofetchLazyInitializer.class);

private static final MethodFilter FINALIZE_FILTER = new MethodFilter() {
    @Override
    public boolean isHandled(Method m) {
        // skip finalize methods
        return !(m.getParameterTypes().length == 0 && m.getName().equals("finalize"));
    }
};

private static final ConcurrentMap<Class<?>, Class<?>> entityFactoryMap = new ConcurrentHashMap<>();

private static final ConcurrentMap<Class<?>, Constructor<?>> entityConstructorMap = new ConcurrentHashMap<>();

//if entityFactoryMap doesnt contain that specific class, add it
private static Class<?> getProxyFactory(Class<?> persistentClass, String idMethodName) {
    // Not sure how enhancer work, but it seems like you tell enhancer what type of subclasses that can be created, and all the method calls will be intercepted by entitycallbackfilter
    if (!entityFactoryMap.containsKey(persistentClass)) {
        ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(persistentClass);
        factory.setInterfaces(new Class[]{TrackableEntity.class});
        factory.setFilter(FINALIZE_FILTER);
        entityFactoryMap.putIfAbsent(persistentClass, factory.createClass());
    }

    return entityFactoryMap.get(persistentClass);
}

private static <T> Constructor<T> getDefaultConstructor(Class<T> clazz) throws NoSuchMethodException {
    Constructor<T> constructor = clazz.getDeclaredConstructor();
    if (!constructor.isAccessible()) {
        constructor.setAccessible(true);
    }

    return constructor;
}

public static Object getProxyInstance(Class persistentClass, String idMethodName, Set<Property> persistentProperties,
                                      ExtentManager extentManager)
        throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

    if (Modifier.isFinal(persistentClass.getModifiers())) {
        // Use the default constructor, because final classes cannot be inherited.
        return useDefaultConstructor(persistentClass);
    }

    Class<?> factory = getProxyFactory(persistentClass, idMethodName);
    try {
        final Object proxy = factory.newInstance();
        ((Proxy) proxy).setHandler(new EntityProxyMethodHandler(persistentProperties, extentManager));
        return proxy;
    } catch (IllegalAccessException | InstantiationException e) {
        return useDefaultConstructor(persistentClass);
    }
}

private static Object useDefaultConstructor(Class<?> clazz) throws NoSuchMethodException, InstantiationException,
        InvocationTargetException, IllegalAccessException {

    if (!entityConstructorMap.containsKey(clazz)) {
        entityConstructorMap.put(clazz, getDefaultConstructor(clazz));
    }

    final Constructor<?> c = entityConstructorMap.get(clazz);

    return c.newInstance((Object[]) null);
}

}

public class EntityProxyMethodHandler implements MethodHandler, Serializable {

private final EntityTracker entityTracker;

public EntityProxyMethodHandler(Set<Property> persistentProperties, ExtentManager extentManager) {
    this.entityTracker = new EntityTracker(persistentProperties, extentManager);
}

@Override
public Object invoke(Object obj, Method thisMethod, Method proceed, Object[] args) throws Throwable {
    if (args.length == 0) {
        if (thisMethod.getName().equals("disableTracking")) {
            boolean oldValue = entityTracker.isTracking();
            entityTracker.setTracking(false);
            return oldValue;
        } else if (thisMethod.getName().equals("enableTracking")) {
            boolean oldValue = entityTracker.isTracking();
            entityTracker.setTracking(true);
            return oldValue;
        } else if (thisMethod.getName().equals("isAccessed")) {
            return entityTracker.isAccessed();
        }
    } else if (args.length == 1) {
        if (thisMethod.getName().equals("addTracker") && thisMethod.getParameterTypes()[0].equals(Statistics.class)) {
            entityTracker.addTracker((Statistics) args[0]);
            return null;
        } else if (thisMethod.getName().equals("addTrackers") && thisMethod.getParameterTypes()[0].equals(Set.class)) {
            @SuppressWarnings("unchecked")
            Set<Statistics> newTrackers = (Set) args[0];
            entityTracker.addTrackers(newTrackers);
            return null;
        } else if (thisMethod.getName().equals("extendProfile") && thisMethod.getParameterTypes()[0].equals(Statistics.class)) {
            entityTracker.extendProfile((Statistics) args[0], obj);
            return null;
        } else if (thisMethod.getName().equals("removeTracker") && thisMethod.getParameterTypes()[0].equals(Statistics.class)) {
            entityTracker.removeTracker((Statistics) args[0]);
            return null;
        }
    }

    entityTracker.trackAccess(obj);

    return proceed.invoke(obj, args);
}

有人知道我如何在这里的方法处理程序中调用真实实体对象吗?

Does anyone know how I could call the real entity object in my method handler here?

这是我运行单元测试时堆栈tracea的一部分,由引起的是无限地"重复的:

Here's a part of the stack tracea when I run a unit test, the caused by is being repeated "infinitely":

    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.autofetch.hibernate.EntityProxyMethodHandler.intercept(EntityProxyMethodHandler.java:105)
    at org.autofetch.test.Employee$HibernateBasicProxy$dbvGRz97.getSupervisor(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.autofetch.hibernate.AutofetchLazyInitializer.intercept(AutofetchLazyInitializer.java:123)
    at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95)
    at org.autofetch.test.Employee$HibernateProxy$PajATc2c.getSupervisor(Unknown Source)
    at org.autofetch.test.ExtentTest.secondLevelSupervisorAccess(ExtentTest.java:533)
    at org.autofetch.test.ExtentTest.testSecondLevelSupervisorAccess(ExtentTest.java:246)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.hibernate.testing.junit4.ExtendedFrameworkMethod.invokeExplosively(ExtendedFrameworkMethod.java:45)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298)
    at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.autofetch.hibernate.EntityProxyMethodHandler.intercept(EntityProxyMethodHandler.java:105)
    at org.autofetch.test.Employee$HibernateBasicProxy$dbvGRz97.getSupervisor(Unknown Source)
    ... 30 more

推荐答案

如果要调用原始方法,则可以使用@SuperMethod Method m@SuperCall Callable<?> c来获取它.

If you want to invoke the original method, you can get hold of it using @SuperMethod Method m or @SuperCall Callable<?> c.

使用可调用代理是开销最小的方法,这样做,您无需掌握参数数组.

Using a callable proxy is the method with the least overhead, doing so, you neither need to get hold of the argument array.

这篇关于Hibernate中使用ByteBuddy代理的MethodHandler陷入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆