Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wrote a custom <code>Check</code> for db uniqueness. Maybe you should customize it.</p> <p><strong>DBUnique.java</strong></p> <pre><code>package models.check; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.sf.oval.configuration.annotation.Constraint; import play.db.jpa.GenericModel; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.PARAMETER }) @Constraint(checkWith = DbUniqueCheck.class) public @interface DBUnique { String message() default DbUniqueCheck.mes; Class&lt;? extends GenericModel&gt; modelClass(); String field() default ""; // field name will be used } </code></pre> <p><strong>DbUniqueCheck.java</strong></p> <pre><code>package models.check; import net.sf.oval.Validator; import net.sf.oval.configuration.annotation.AbstractAnnotationCheck; import net.sf.oval.context.FieldContext; import net.sf.oval.context.OValContext; import org.apache.commons.lang.StringUtils; import play.db.jpa.GenericModel.JPAQuery; @SuppressWarnings("serial") public class DbUniqueCheck extends AbstractAnnotationCheck&lt;DBUnique&gt; { final static String mes = "validation.dbunique"; DBUnique dbUnique; @Override public void configure(DBUnique dBUnique) { this.dbUnique = dBUnique; setMessage(dBUnique.message()); } public boolean isSatisfied(Object validatedObject, Object value, OValContext context, Validator validator) { try { String field = dbUnique.field(); if (field == null || field.isEmpty()) { field = ((FieldContext) context).getField().getName(); } JPAQuery q = (JPAQuery) dbUnique.modelClass().getMethod("find", String.class, Object[].class) .invoke(null, "by" + StringUtils.capitalize(field), new Object[] { value }); return q.first() == null; } catch (Exception e) { e.printStackTrace(); } return false; } } </code></pre> <p>usage : <a href="https://gist.github.com/hgo/5227028" rel="nofollow">link to gist</a></p> <p>it simply checks the given <code>field</code> for given <code>class</code> instance is unique in db. Maybe you should make something like these..</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload