Search code examples
activejdbc

ActiveJDBC UniquenessValidator on non-persisted objects


I have the following model:

Car (
  id   INT(11) NOT NULL AUTO_INCREMENT,
  name TEXT
)

..

public class Car extends Model {


    static{
        validatePresenceOf("name");
        validateWith(new UniquenessValidator("name"));
    }

    public Car() {}


}

In this model, I am specifying the name of all cars to be unique.

Running the following code doesn't throw a validation error on 2nd instance:

Car acura_1 = new Car();
acura_1.set("name","Acura");
acura_1.saveIt();

Car acura_2 = new Car();
acura_2.set("name","Acura");
acura_2.saveIt(); // << surprisingly, this works!

//acura_2.isValid(); 

I was expecting a validation exception to rise on the acura_2.saveIt() since the name "Acura" is already taken/present in the table cars (ie. when acura_1 was persisted).

Looking at the code of UniquenessValidator, it looks like the validation of the uniqueness takes into account the id of the model, if I am not mistaken.

If the last commented-line is executed (acura_2.isValid()), then the error message is present on acura_2: name -> should be unique.

I was wondering how come the UniquenessValidator works only on persisted objects?


Solution

  • You are correct, this validator is not the best. This issue was fixed: https://github.com/javalite/activejdbc/issues/572 and JavaDoc added for UniquenessValidator

    Generally speaking, I would not advise using this validator in a production system because it does not actually guarantee uniqueness. Please, see the JavaDoc for arguments.