use of org.molgenis.data.meta.AttributeType.ONE_TO_MANY in project molgenis by molgenis.
the class RestService method updateMappedByEntitiesOneToMany.
/**
* For entities with the given attribute that is part of a bidirectional one-to-many relationship update the other side of the relationship.
*
* @param entity created or updated entity
* @param existingEntity existing entity
* @param attr bidirectional one-to-many attribute
*/
private void updateMappedByEntitiesOneToMany(@Nonnull Entity entity, @Nullable Entity existingEntity, @Nonnull Attribute attr) {
if (attr.getDataType() != ONE_TO_MANY || !attr.isMappedBy()) {
throw new IllegalArgumentException(format("Attribute [%s] is not of type [%s] or not mapped by another attribute", attr.getName(), attr.getDataType().toString()));
}
// update ref entities of created/updated entity
Attribute refAttr = attr.getMappedBy();
Stream<Entity> stream = stream(entity.getEntities(attr.getName()).spliterator(), false);
if (existingEntity != null) {
// filter out unchanged ref entities
Set<Object> refEntityIds = stream(existingEntity.getEntities(attr.getName()).spliterator(), false).map(Entity::getIdValue).collect(toSet());
stream = stream.filter(refEntity -> !refEntityIds.contains(refEntity.getIdValue()));
}
List<Entity> updatedRefEntities = stream.map(refEntity -> {
if (refEntity.getEntity(refAttr.getName()) != null) {
throw new MolgenisDataException(format("Updating [%s] with id [%s] not allowed: [%s] is already referred to by another [%s]", attr.getRefEntity().getId(), refEntity.getIdValue().toString(), refAttr.getName(), entity.getEntityType().getId()));
}
refEntity.set(refAttr.getName(), entity);
return refEntity;
}).collect(toList());
// update ref entities of existing entity
if (existingEntity != null) {
Set<Object> refEntityIds = stream(entity.getEntities(attr.getName()).spliterator(), false).map(Entity::getIdValue).collect(toSet());
List<Entity> updatedRefEntitiesExistingEntity = stream(existingEntity.getEntities(attr.getName()).spliterator(), false).filter(refEntity -> !refEntityIds.contains(refEntity.getIdValue())).map(refEntity -> {
refEntity.set(refAttr.getName(), null);
return refEntity;
}).collect(toList());
updatedRefEntities = Stream.concat(updatedRefEntities.stream(), updatedRefEntitiesExistingEntity.stream()).collect(toList());
}
if (!updatedRefEntities.isEmpty()) {
dataService.update(attr.getRefEntity().getId(), updatedRefEntities.stream());
}
}
Aggregations