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?