Activejdbc Compound Validation

Asked

Viewed 69 times

2

I need to do a composite validation on the Activejdbc ORM and I’m not finding anything in the documentation. Something like, extends from the Validatoradapter class, but I’m not finding material to use as an example.

Basically:

public class Competencia extends Model{

  static{
    validateWith(new UniquenessValidator("mes", "ano")).message("O número de documento já existe");
  }

}

I managed to make (picked up from a friend) the Uniqueness with a field, but I’m having difficulties to make for two fields. How can I get around this difficulty, will anyone have some similar example?

  • 1

    I guess you’ll have to write your own Validator based on the UniquenessValidator. For example, getting a vararg String... attributes and modifying the method validate to consider all attributes received in the query. If you do this check that the table is properly indexed or the solution will suffer due to performance of consultation.

1 answer

1


package #.#.#.#.#.dominio.validacoes;

import org.javalite.activejdbc.Base;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.ModelDelegate;
import org.javalite.activejdbc.validation.ValidatorAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

public class UKValidator extends ValidatorAdapter {

    public static final String CODIGO = "V0001";
    public static final String DESCRICAO = "Restrição de chave única violada";

    private final String[] attributes;

    private UKValidator() {
        attributes = null;
    }

    public UKValidator(String... attributes) {
        this.attributes = attributes;
    }

    @Override
    public void validate(Model model) {
        StringJoiner sj = new StringJoiner(" AND ");
        List<Object> params = new ArrayList<>();

        for (String attribute : attributes) {
            sj.add(attribute + " = ?");
            params.add(model.get(attribute));
        }

        Long count = Base.count(ModelDelegate.metaModelOf(model.getClass()).getTableName(),
                sj.toString(),
                params.toArray());

        if (count > 0) {
            model.addError(CODIGO, String.format("%s: %s", DESCRICAO, toString()));
        }
    }


    @Override
    public String toString() {
        return Arrays.toString(attributes);
    }
}

Serves?

  • Is there a way to call validation ONLY in create? Considering I’m in editing, I wouldn’t need to validate again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.