我实现了自己的验证器,它实现了接口javax.faces.Validator。对于我的验证,我需要一个EntityManager来创建一个查询。这是我的代码:
@FacesValidator(value = "userAliasValidator")
public class UserAliasValidator implements Validator {
@PersistenceUnit
private EntityManagerFactory emf;
private EntityManager em;
@Override
public void validate(FacesContext context, UIComponent component,
Object object) throws ValidatorException {
em = emf.createEntityManager();
Query query = em.createNamedQuery("SelectUserByAlias");
String alias = String.valueOf(object);
query.setParameter("alias", alias);
List<User> result = query.getResultList();
if (result.size() > 0) {
FacesContext.getCurrentInstance()
.addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"User allready exists",
"Please try another name!"));
}
}
}
不幸的是,这不起作用。如何在验证器中使用EntityManager?