ActiveJdbc Validation Compound

2

I need to do a composite validation in ORJ ActiveJdbc and I'm not finding anything in the documentation. Something of the type, 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 was able to (I picked up from a friend) the Uniqueness with a field, but I'm having trouble making two fields. How can I get around this difficulty, does anyone have a similar example?

    
asked by anonymous 26.05.2016 / 03:48

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);
    }
}

Serve?

    
26.10.2016 / 20:06