I'm using Play's CRUD module to create a simple set of admin screens. One of my models is User and I want to enforce a unique constraint on the email field.
The code looks like this:
public class User extends Model {
    @Email
    @Required
    @Column(unique=true)
    public String email;
The admin screen displays correctly - when I try to break uniqueness (by saving a user with an already used email) I get this error (in the browser):
Execution exception
PersistenceException occured : org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
In {module:crud}/app/controllers/CRUD.java (around line 100)
96:
             } catch (TemplateNotFoundException e) {
97:
                 render("CRUD/show.html", type, object);
98:
             }
99:
         }
100:
         <b>object._save();</b>
101:
         flash.success(Messages.get("crud.saved", type.modelName));
102:
         if (params.get("_save") != null) {
103:
             redirect(request.controller + ".list");
104:
         }
105:
         redirect(request.controller + ".show", object._key());
106:
     }
Are there any tweaks I can make to use the CRUD module AND column uniqueness annotations?
You can create a custom check and add to the email property in the User class.
public class UniqueCheck extends Check {
    @Override
    public boolean isSatisfied(Object validatedObject, Object value) {
        if (StringUtils.isBlank((String) value)) {
            return false;
        }
        return User.findByEmail((String) value));
    }
}
Then
public class User extends Model {
@Email
@Required
@MaxSize(value = 250)
@CheckWith(value = UniqueEmail.class, message = "Existing account has been found with this e-mail")
public String email;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With