use of com.axelor.db.Model in project axelor-open-suite by axelor.
the class ModelTool method apply.
/**
* Apply consumer to each record found from collection of IDs.
*
* @param ids collection of IDs.
* @param consumer to apply on each record.
* @return the number of errors that occurred.
*/
public static <T extends Model> int apply(Class<? extends Model> modelClass, Collection<? extends Number> ids, ThrowConsumer<T> consumer) {
Preconditions.checkNotNull(ids, I18n.get("The collection of IDs cannot be null."));
Preconditions.checkNotNull(consumer, I18n.get("The consumer cannot be null."));
int errorCount = 0;
for (Number id : ids) {
try {
if (id != null) {
Model model = JPA.find(modelClass, id.longValue());
if (model != null) {
consumer.accept((T) model);
continue;
}
}
throw new AxelorException(modelClass, TraceBackRepository.CATEGORY_NO_VALUE, I18n.get("Cannot find record #%s"), String.valueOf(id));
} catch (Exception e) {
++errorCount;
TraceBackService.trace(e);
} finally {
JPA.clear();
}
}
return errorCount;
}
use of com.axelor.db.Model in project axelor-open-suite by axelor.
the class ModelTool method checkUniqueFields.
/**
* Get set of fields affected by unique constraint error.
*
* @param model
* @return
*/
private static Set<Field> checkUniqueFields(Model model) {
Set<Field> errors = new HashSet<>();
Class<? extends Model> modelClass = EntityHelper.getEntityClass(model);
for (Field field : modelClass.getDeclaredFields()) {
Column column = field.getAnnotation(Column.class);
if (column == null || !column.unique()) {
continue;
}
String filter = String.format("self.%s = :value", field.getName());
String getterName = fieldNameToGetter(field.getName());
try {
Method getter = modelClass.getMethod(getterName);
Object value = getter.invoke(model);
Model existing = JPA.all(modelClass).filter(filter).bind("value", value).fetchOne();
if (existing != null && !existing.getId().equals(model.getId())) {
errors.add(field);
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
TraceBackService.trace(e);
}
}
return errors;
}
Aggregations