Search code examples
javahibernateproxycglib

make hibernate save custom made cgproxy values


So I need to use my own cglib proxy for Entities. Problem is that when I am saving it into database, all values are null, even-though I would expect that hibernate gets the values with getters - that would get them through the proxy from the original entity. But it seems like it takes the values some other way. My question is, how do I enhance the proxy or update hibernate config so that it saves the values of original? It does the same thing with its own proxies after all, so there must be some way. Here is an example:

class Something {
    private String name;
    private String description;

    // constructor, getters, setters
}

class Foo {

    public Something create() {
        Something something = new Something("some name", "some description");
        return (Something) Enhancer.create(Something.class, new Handler(something));
    }

    class Handler implements MethodInterceptor {
        private final Something original;

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            // do some clever stuff
            return method.invoke(original, objects);
        }
    }
}

class DbHandler {
    // Autowired or...
    private SomethingRespository somethingRespository;

    public void handle(Foo foo) {
        Something proxy = foo.create();
        somethingRepository.save(proxy); // saves null, null instead of "some name", "some description"
    }
}

Solution

  • You will have to use property access rather than field access if you want this. This means, you put all the annotations on the getters rather than the fields.