I disagree with handling ConstraintException. I have written a validator that checks duplicates before saving, and it works great.
Here is an example checking duplicate emails.
@Name("emailValidator")
@Validator
@BypassInterceptors
@Transactional
public class UniqueEmailValidator implements javax.faces.validator.Validator, Serializable {
private static final long serialVersionUID = 6086372792387091314L;
@SuppressWarnings("unchecked")
public void validate(FacesContext facesContext, UIComponent component, Object value) throws ValidatorException {
EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");
String newEmail = (String) value;
String oldEmail = String.valueOf(component.getAttributes().get("oldEmail"));
if (oldEmail != null && !oldEmail.equalsIgnoreCase(newEmail)) {
List<User> users = entityManager.createQuery(
"SELECT DISTINCT u FROM " + User.class.getName() + " p where lower(p.fromEmail) = :email").setParameter("email",
newEmail.toLowerCase()).getResultList();
if (!users.isEmpty()) {
Map<String, String> messages = Messages.instance();
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.get("admin.emailexists"), messages
.get("admin.emailexists")));
}
}
}
}
And in your form (xhtml) you write:
<s:decorate template="/layout/definition.xhtml">
<ui:define name="label">#{messages['processdata.email']}</ui:define>
<h:inputText id="fromEmail" size="30" required="true" value="# {userAdmin.existingUser.fromEmail}">
<f:validator validatorId="emailValidator"/>
<f:attribute name="oldEmail" value="#{userAdmin.existingUser.fromEmail}" />
<s:validate />
</h:inputText>
</s:decorate>
This way it will always validate the field before saving. You can even put an a:support tag to validate when focus is changed.