玩! - 独特的模型领域 [英] Play! - unique model field
问题描述
如何让我的模型类字段独一无二?例如。如果已经登录,我想为用户显示正确的消息。我必须编写自己的验证检查并使用它,或者可以使用JPA @UniqueConstraint
?
How can I make my model class fields unique? Eg. if login is already taken, I'd like to display proper message for the user. I have to write my own validation check and use it, or JPA @UniqueConstraint
can be used?
推荐答案
我这样做了:
@Entity
public class User extends Model {
@Basic(optional=false) @Column(unique=true) public String name;
public User(String name) {
this.name = name;
create();
}
/** used in registration to find name clash */
public static User findByName(String name) {
return find("name", name).first();
}
}
然后在你做的控制器中类似于:
and then in the controller you do something like:
public static void register(@Required String name) {
if(User.findByName(name)!=null) {
Validation.addError("name", "this name is not available");
}
if (validation.hasErrors()) {
validation.keep();
params.flash();
flash.error("Please correct the form data.");
signup(); // whatever your GET action was
}
User user = new User(name);
login(); // whatever your success action is
}
你可以在没有User.findByName的情况下做到这一点()检查,你会得到一个ConstrainViolationException但当然不是非常用户友好。您也可以尝试/捕获该异常。我更喜欢这两种方式,用户友好且在数据库中保持一致。
you could do it without the User.findByName() check and you would get a ConstrainViolationException but which is of course not very user friendly. You could also just try/catch that exception. I prefer it both ways, being user friendly and consistent in the database.
这篇关于玩! - 独特的模型领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!