Skip to content

Instantly share code, notes, and snippets.

@giates
Created Jul 17, 2012
Embed
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:
https://groups.google.com/forum/#!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:
app/constraints
app/constraints/impl
app/models
put Unique.java into app/constraints folder
put UniqueValidator.java into app/constraints/impl folder
put User.java into app/models folder
put ModelTest.java 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
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 play.data.validation.Validation;
import java.util.Collection;
public class ModelTest {
@Test
public void createNewUser() {
running(fakeApplication(), new Runnable() {
public void run() {
User user1 = new User();
user1.setName("goofy");
user1.setPassword("123");
user1.save();
User user2 = new User();
user2.setName("goofy");
user2.setPassword("345");
Collection errors = Validation.getValidator().validate(user2);
assertThat(errors.size()).isEqualTo(1);
user2.setName("donald");
errors = Validation.getValidator().validate(user2);
assertThat(errors.size()).isEqualTo(0);
user2.save();
user2 = User.find.where().eq("name", "donald").findUnique();
user2.setName("goofy");
errors = Validation.getValidator().validate(user2);
assertThat(errors.size()).isEqualTo(1);
user2 = User.find.where().eq("name", "donald").findUnique();
user2.setName("scrooge");
errors = Validation.getValidator().validate(user2);
assertThat(errors.size()).isEqualTo(0);
user2.save();
}
});
}
}
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")
* })
*/
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = UniqueValidator.class)
@Documented
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
*/
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@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;
@Override
public void initialize(final Unique constraintAnnotation)
{
this.modelClass = constraintAnnotation.modelClass();
this.idClass = constraintAnnotation.idClass();
fields = constraintAnnotation.fields();
}
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context)
{
try
{
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 play.data.format.*;
import play.data.validation.*;
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.List({
@Unique(modelClass = User.class, fields = {"name"}, message = "Name already exists !"),
@Unique(modelClass = User.class, fields = {"password"}, message = "Password already exists !")
})
@Entity
public class User extends Model {
@Id
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Constraints.Required
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Constraints.Required
//@Constraints.ValidateWith(value=MyValidator.class)
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

Hi

I like your validator but it does not seem to work in combination with Forms;
http://stackoverflow.com/questions/14894814/validator-with-target-type-does-not-fill-errors-list-in-playframework-form

Do you experience the same problem?

BR, Rene

Copy link

ghost commented Jun 3, 2015

Hey,
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