0

I implemented my own validator, which implements the interface javax.faces.Validator. For my validation I need an EntityManager to create a query. This is my code:

@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!"));
        }
    }
}

Unfortunately this doesn't work. How can I use a EntityManager in my validator?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
John
  • 735
  • 2
  • 14
  • 32
  • Please clarify what does it mean "this doesn't work"? Did some exception throw? if yes than you can show us stack trace this exception. And you can write how you declare your EntityManager. – Alexey Semenyuk Sep 27 '14 at 13:26
  • So, I can assume that you need to use @PersistenceContext annotation and to have a persistence.xml in your project. For more details you may read this links http://tomee.apache.org/examples-trunk/injection-of-entitymanager/README.html , http://stackoverflow.com/questions/4727920/injecting-entity-manager-into-managed-bean – Alexey Semenyuk Sep 27 '14 at 13:31

0 Answers0