我需要检查应用程序中字段的唯一性。
我尝试使用Hibernate @Unique
约束,但它显示了堆栈跟踪,但在用户表单中没有错误消息。
我的下一个解决方案是编写自定义验证器,但我认为有更好的解决方案。
在JSF中有更简单的方法吗?
(JSF 2.1 + RichFaces)
答案 0 :(得分:2)
我为我的基础实体破解了一个快速的脏工作解决方案,用于JSF 2.1唯一密钥验证:
用法:
<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>
验证
@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);
}
}
}
答案 1 :(得分:0)
您可以手动验证bean的ajax请求。手动验证的一个例子如下所示。
ClassValidator<TestClass> classValidator = new ClassValidator<TestClass>(
TestClass.class );
InvalidValue[] invalidValues = classValidator
.getInvalidValues(testObject);
for (InvalidValue invalidValue : invalidValues) {
System. out .println( "Property Name: "
+ invalidValue.getPropertyName() + " Message: "
+ invalidValue.getMessage());
}
您可以使用<a4j:support />
代码
答案 2 :(得分:0)
您可以在<f:ajax />
上使用onblur
或textfield
事件,并在您的支持bean中验证非model
的所有null
值。
<h:message id="errorMessageTag" for="fieldId"/>
<h:inputText id="fieldId" value="#{beanName.modelName.variableName}">
<f:ajax event="blur" listener="#{beanName.property}" render="errorMessageTag" />
</h:inputText>