private void validateEntityValueUniqueness( Entity entity, ValidationResource validationResource, ValidationMode validationMode) { validationResource .getUniqueAttrs() .forEach( uniqueAttr -> { Object attrValue = entity.get(uniqueAttr.getName()); if (attrValue != null) { if (uniqueAttr.getDataType() instanceof XrefField) { attrValue = ((Entity) attrValue).getIdValue(); } HugeMap<Object, Object> uniqueAttrValues = validationResource.getUniqueAttrsValues().get(uniqueAttr.getName()); Object existingEntityId = uniqueAttrValues.get(attrValue); if ((validationMode == ValidationMode.ADD && existingEntityId != null) || (validationMode == ValidationMode.UPDATE && existingEntityId != null && !existingEntityId.equals(entity.getIdValue()))) { ConstraintViolation constraintViolation = new ConstraintViolation( format( "Duplicate value '%s' for unique attribute '%s' from entity '%s'", attrValue, uniqueAttr.getName(), getName()), uniqueAttr, Long.valueOf(validationResource.getRow())); validationResource.addViolation(constraintViolation); } else { uniqueAttrValues.put(attrValue, entity.getIdValue()); } } }); }
private void initUniqueValidation(ValidationResource validationResource) { // get unique attributes List<AttributeMetaData> uniqueAttrs = StreamSupport.stream(getEntityMetaData().getAtomicAttributes().spliterator(), false) .filter(attr -> attr.isUnique() && attr.getExpression() == null) .collect(Collectors.toList()); // get existing values for each attributes if (!uniqueAttrs.isEmpty()) { Map<String, HugeMap<Object, Object>> uniqueAttrsValues = new HashMap<>(); Fetch fetch = new Fetch(); uniqueAttrs.forEach( uniqueAttr -> { uniqueAttrsValues.put(uniqueAttr.getName(), new HugeMap<>()); fetch.field(uniqueAttr.getName()); }); Query q = new QueryImpl().fetch(fetch); decoratedRepository .findAll(q) .forEach( entity -> { uniqueAttrs.forEach( uniqueAttr -> { HugeMap<Object, Object> uniqueAttrValues = uniqueAttrsValues.get(uniqueAttr.getName()); Object attrValue = entity.get(uniqueAttr.getName()); if (attrValue != null) { if (uniqueAttr.getDataType() instanceof XrefField) { attrValue = ((Entity) attrValue).getIdValue(); } uniqueAttrValues.put(attrValue, entity.getIdValue()); } }); }); validationResource.setUniqueAttrsValues(uniqueAttrsValues); } validationResource.setUniqueAttrs(uniqueAttrs); }
@Override public void close() { if (refEntitiesIds != null) { for (HugeSet<Object> refEntityIds : refEntitiesIds.values()) { try { refEntityIds.close(); } catch (IOException e) { throw new RuntimeException(e); } } } if (uniqueAttrsValues != null) { for (HugeMap<Object, Object> uniqueAttrValues : uniqueAttrsValues.values()) { try { uniqueAttrValues.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }