Skip to content

Instantly share code, notes, and snippets.

Created Jul 17, 2012
What would you like to do?
Play framework 2 Unique Constraint using Java/Ebean
Unique constraint for Play! Framework 2.x using Java/Ebean.
After some experiments, thanks to many posts readed in google group, finally I've figured out how to write
a first version of a usable UniqueConstraint for play2 based on original idea of Dmitriy Arkhipov found here:!topic/play-framework/Jn4sJ9Jx8sY
The sources is far from perfect but I think this should be useful enough.
Warning: my code must be tested with column numbers (integers & decimals), dates and booleans.
To test it just create a Play2 java project (play new test-unique) then create these folders:
put into app/constraints folder
put into app/constraints/impl folder
put into app/models folder
put into test folder
test it using play test
Have fun !
Copyright [2012] [Gianluca Tessarolo]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.
import org.junit.*;
import java.util.*;
import play.mvc.*;
import play.test.*;
import play.libs.F.*;
import static play.test.Helpers.*;
import static org.fest.assertions.Assertions.*;
import models.*;
import com.avaje.ebean.*;
import javax.validation.Validator;
import java.util.Collection;
public class ModelTest {
public void createNewUser() {
running(fakeApplication(), new Runnable() {
public void run() {
User user1 = new User();
User user2 = new User();
Collection errors = Validation.getValidator().validate(user2);
errors = Validation.getValidator().validate(user2);
user2 = User.find.where().eq("name", "donald").findUnique();
errors = Validation.getValidator().validate(user2);
user2 = User.find.where().eq("name", "donald").findUnique();
errors = Validation.getValidator().validate(user2);
package constraints;
import constraints.impl.UniqueValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
import play.db.ebean.*;
* Validation annotation to check unique constraint/
* An array of fields can be supplied.
* Example, check uniqueness on code
* @Unique(modelClass = User.class, fields = {"code"}, message = "Record has already been taken")
* Example, check uniqueness on more fields
* @Unique.List({
* @Unique(modelClass = User.class, fields = {"code"}, message = "Code has already been taken"),
@Unique(modelClass = User.class, fields = {"name"}, message = "Name has already been taken"),
@Unique(modelClass = User.class, fields = {"name", "published"}, message = "Name has already been taken on published status")
* })
@Constraint(validatedBy = UniqueValidator.class)
public @interface Unique
String message() default "{constraints.unique}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<? extends Model> modelClass();
Class<?> idClass() default Long.class;
* @return The fields
String[] fields();
* Defines several <code>@Unique</code> annotations on the same element
* @see Unique
@interface List
Unique[] value();
package constraints.impl;
import constraints.Unique;
import org.apache.commons.beanutils.BeanUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import play.db.ebean.*;
import com.avaje.ebean.ExpressionList;
public class UniqueValidator implements ConstraintValidator<Unique, Object>
private Class<? extends Model> modelClass;
private Class<?> idClass;
private String[] fields;
public void initialize(final Unique constraintAnnotation)
this.modelClass = constraintAnnotation.modelClass();
this.idClass = constraintAnnotation.idClass();
fields = constraintAnnotation.fields();
public boolean isValid(final Object value, final ConstraintValidatorContext context)
Model.Finder<?, ? extends Model> find = new Model.Finder(idClass, modelClass);
ExpressionList el = find.where();
for (String f : fields) {
el.eq(f, BeanUtils.getProperty(value, f));
Model record = (Model) el.findUnique();
boolean recordFound = record != null;
boolean sameRecord = false;
boolean recordValid = false;
Long modelId = null;
Long currentId = null;
if (recordFound) {
modelId = new Long(BeanUtils.getProperty(record, "id"));
try {
currentId = new Long(BeanUtils.getProperty(value, "id"));
} catch (Exception e) {
currentId = new Long(0);
sameRecord = currentId.longValue() == modelId.longValue();
recordValid = !recordFound || sameRecord;
// Some debug...
// System.out.println(">>> searching name = " + BeanUtils.getProperty(record, "name"));
// System.out.println(">>> record found ? " + recordFound);
// System.out.println(">>> same record ? " + sameRecord);
// System.out.println(">>> record valid ? " + recordValid;
return recordValid;
catch (final Exception ignore)
// FIXME: ignored exception, WARNING...
return true;
package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import com.avaje.ebean.*;
import play.libs.F.Tuple;
import constraints.*;
import constraints.impl.*;
* Computer entity managed by Ebean
//@FieldMatch(modelClass = User.class, first = "name", second = "password", message = "The password fields must match")
@Unique(modelClass = User.class, fields = {"name"}, message = "Name already exists !"),
@Unique(modelClass = User.class, fields = {"password"}, message = "Password already exists !")
public class User extends Model {
private Long id;
public Long getId() {
return id;
public void setId(Long id) { = id;
private String name;
public String getName() {
return name;
public void setName(String name) { = name;
private String password;
public String getPassword() {
return password;
public void setPassword(String password) {
this.password = password;
* Generic query helper for entity User with id Long
public static Finder<Long,User> find = new Finder<Long,User>(Long.class, User.class);
Copy link

ghost commented Feb 15, 2013


I like your validator but it does not seem to work in combination with Forms;

Do you experience the same problem?

BR, Rene

Copy link

ghost commented Jun 3, 2015

how can I get a feedback message while saving either if record already exists in database or not exists.
Thanks for help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment