Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to configure the Play Framework's CRUD module to respect @Column(unique=true) annotations?

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?

like image 639
Harry Blundun Avatar asked May 24 '11 11:05

Harry Blundun


1 Answers

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;

}
like image 91
Felipe Oliveira Avatar answered Oct 13 '22 10:10

Felipe Oliveira