2

I'm cloning an entity using Spring BeanUtils.copyProperties(source, target, excludes) method and the issue is there is a method called setHandler that gets called and it basically resets all the properties I set in my exclusion list during the copy. If I exclude handler, then I get an exception saving the new object.

I just want to do a clone of a Hibernate object, excluding 10 properties and save the new object.

    public static <T> T cloneClass(T existing, Class<? extends Annotation> ignores)
        throws Exception {

    final Collection<String> excludes = new ArrayList<>();

    Set<Method> annotated = getMethodsWithAnnotation(ignores, existing.getClass());

    for (Method method : annotated) {

        if (!method.getName().startsWith("get") && !method.getName().startsWith("is"))
            continue;
        String exclude = ReflectUtil.decap(method.getName());
        log.debug("Exclude from copy: " + exclude);
        excludes.add(exclude);
    }

    excludes.add("handler"); <-- must have this
    Object newInstance = existing.getClass().newInstance();
    String[] excludeArray = excludes.toArray(new String[excludes.size()]);

    BeanUtils.copyProperties(existing, newInstance, excludeArray);

    return (T) newInstance;
}

If I don't include

excludes.add("handler"); <-- must have this

Then what happens is the target object gets all the properties from the source and basically makes my exclude list useless, but once I try to save that object, Hibernate throws an internal hibernate error.

Is there an easier way to clone an object than what I am doing?

chrislhardin
  • 1,747
  • 1
  • 28
  • 44
  • what exception is hibernate throwing? – Amer Qarabsa Nov 14 '17 at 21:38
  • Actually nevermind the error... .There is no error... The cloned instance just comes out exactly the same as the original. Reflection gets to setHandler and the entire object becomes populated for some reason. – chrislhardin Nov 15 '17 at 15:48

1 Answers1

0

I don't think you really need to do any cloning. Simply retrieve the object and then remove the object from the session and it is effectively a clone: Is it possible to detach Hibernate entity, so that changes to object are not automatically saved to database?. Start another session again once you want to update the instance.

Derrops
  • 7,651
  • 5
  • 30
  • 60