开发者

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?


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;

}


It sounds to me like the system is doing just what you expected. The only thing I can imagine is patching the CRUD module to catch this exception and be nicer, but generally unique constraints are database-side constraints and can only be checked by trying to write to the database. So a unique constraint is not a validation annotation (which can be executed before writing to the database).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜