2 Replies Latest reply on Apr 10, 2012 2:33 AM by paul_

    Getting EntityManager in FacesValidator

    paul_

      Hope i'm not asking a question already answered (at least I couldn't find any)

       

      I am writing a JEE 6 webapp with Seam 3.1, JSF 2 (Richfaces 4.1) running on JBoss 7.1 final.

       

      For the past few hours I was trying to get an EntityManager injected into a FacesValidator like this:

       

      @FacesValidator("ValidatorUsernameReg")

      public class ValidatorUsernameReg implements Validator {

      ...

      @PersistenceContext

      private EntityManager em;

       

       

      @Override

          public void validate(FacesContext arg0, UIComponent arg1, Object arg2)

                  throws ValidatorException {

           em.createNativeQuery(...)

      }

       

      }

       

      I need the EntityManager here to check if a username entered in a registration form already has been taken and then display a corresponding error message.

       

      But, and that's my problem, the EntityManager always turns out null.

       

      Is there a way other than creating a corresponding Session Bean which queries the database?

      Is persistence-related stuff not allowed / not possible in JSF Validators?

       

      Greetings from Germany,

      pascal

        • 1. Re: Getting EntityManager in FacesValidator
          lightguard

          If you're using Seam Faces you can @Inject an EntityManager. People are typically doing a Seam Managed Persistence Context for this. Another way would be to @Inject another component which has the @PersistenceContext in it.

          • 2. Re: Getting EntityManager in FacesValidator
            paul_

            Yea, I ended up injecting another component that uses @PersistenceContext.

             

            As far as I get it, one can't use @PersistenceContext in a validator because it isn't a bean managed by the container.

             

            Anyhow, Thanks Jason for your reply.

             

            Greetings from Germany

             

            p.salg