I hacked away a quick'n dirty working solution for JSF 2.1 unique key validation for my base entities:
usage:
<p:inputText id="name" value="#{employeesController.currentEmployee.name}">
<f:validator validatorId="uniqueColumnValidator" />
<f:attribute name="currentEntity" value="#{employeesController.currentEmployee}" />
<f:attribute name="uniqueColumn" value="name" />
</p:inputText>
validator:
@RequestScoped
@FacesValidator("uniqueColumnValidator")
public class UniqueColumnValidator implements Validator, Serializable {
@PersistenceContext
protected EntityManager em;
/**
* generic unique constraint validator for AbstractBaseEntity entities<br />
* requires the following additional attributes on the form element ("<f:attribute>"):<br />
* - "currentEntity" the entity instance (used for getting the class and guid)<br />
* - "uniqueColumn" the column where the new value will be checked for uniqueness
*/
@Override
public void validate(final FacesContext context, final UIComponent comp, final Object newValue) throws ValidatorException {
AbstractBaseEntity currentEntity = (AbstractBaseEntity) comp.getAttributes().get("currentEntity");
String uniqueColumn = (String) comp.getAttributes().get("uniqueColumn");
boolean isValid = false;
try {
em.createQuery(
"FROM " + currentEntity.getClass().getSimpleName()
+ " WHERE " + uniqueColumn + " = :value"
+ " AND guid <> :guid", currentEntity.getClass())
.setParameter("value", value)
.setParameter("guid", currentEntity.getGuid())
.getSingleResult();
} catch (NoResultException ex) {
isValid = true; // good! no result means unique validation was OK!
}
if (!isValid) {
FacesMessage msg = Messages.createError("must be unique", uniqueColumn);
context.addMessage(comp.getClientId(context), msg);
throw new ValidatorException(msg);
}
}
}