Алексей, возможное решение это скопировать метод deepCopy и исключить копирование существуюшего id. Так же вы сможете в будующем добавить свою логику связанную с копированием сущностей. Например, некоторые сущности не копировать.
Пример нового метода копирования:
Test
public void testDeepCopy() throws Exception {
User user = new User();
UserRole userRole = new UserRole();
userRole.setUser(user);
List<UserRole> userRoles = new ArrayList<>();
userRoles.add(userRole);
user.setUserRoles(userRoles);
MetadataTools tools = metadata.getTools();
User newUser = new User();
deepCopy(user, newUser, new EntitiesHolder());
assertNotEquals(user.getId(), newUser.getId());
assertNotEquals(user.getUserRoles().get(0).getId(), newUser.getUserRoles().get(0).getId());
}
public void deepCopy(Entity source, Entity destination, EntitiesHolder entitiesHolder) {
Metadata metadata = AppBeans.get(Metadata.class);
PersistentAttributesLoadChecker persistentAttributesLoadChecker = AppBeans.get(PersistentAttributesLoadChecker.class);
for (MetaProperty srcProperty : source.getMetaClass().getProperties()) {
String name = srcProperty.getName();
if (srcProperty.isReadOnly() || !persistentAttributesLoadChecker.isLoaded(source, name)) {
continue;
}
Object value = source.getValue(name);
if (value == null) {
continue;
}
String idProperty = metadata.getTools().getPrimaryKeyName(source.getMetaClass());
//исключаем копирование pk
if (name.equals(idProperty)) {
continue;
}
if (srcProperty.getRange().isClass()) {
Class refClass = srcProperty.getRange().asClass().getJavaClass();
if (!metadata.getTools().isPersistent(refClass)) {
continue;
}
if (srcProperty.getRange().getCardinality().isMany()) {
//noinspection unchecked
Collection<Entity> srcCollection = (Collection) value;
Collection<Entity> dstCollection = value instanceof List ? new ArrayList<>() : new LinkedHashSet<>();
for (Entity srcRef : srcCollection) {
Entity reloadedRef = entitiesHolder.find(srcRef.getId());
if (reloadedRef == null) {
reloadedRef = entitiesHolder.create(srcRef.getClass(), srcRef.getId());
deepCopy(srcRef, reloadedRef, entitiesHolder);
}
dstCollection.add(reloadedRef);
}
destination.setValue(name, dstCollection);
} else {
Entity srcRef = (Entity) value;
Entity reloadedRef = entitiesHolder.find(srcRef.getId());
if (reloadedRef == null) {
reloadedRef = entitiesHolder.create(srcRef.getClass(), srcRef.getId());
deepCopy(srcRef, reloadedRef, entitiesHolder);
}
destination.setValue(name, reloadedRef);
}
} else {
destination.setValue(name, value);
}
}
}
public static class EntitiesHolder {
protected Map<Object, Entity> cache = new HashMap<>();
public Entity create(Class<? extends Entity> entityClass, Object id) {
Entity entity = cache.get(id);
if (entity == null) {
Metadata metadata = AppBeans.get(Metadata.class);
entity = metadata.create(entityClass);
cache.put(id, entity);
}
return entity;
}
public Entity find(Object id) {
return cache.get(id);
}
}