2 Replies Latest reply on Feb 23, 2010 11:14 PM by vinitadhopia

    EntityManagers in Application-scoped Startup components

    vinitadhopia

      Hello all,


      I'm trying to utilize Hibernate Search for searching within my application.  I am attempting to create an application-scoped component, marked with @Startup which will build the initial index of all the relevant entities.  I am injecting the entityManager and the method that does the indexing is marked with @PostConstruct, since I want the method invoked after all injections have occurred.


      However, the entityManager keeps coming up null, causing an NPE.  I'm not entirely sure what I'm doing wrong that prevents the entityManager from being injected.


      I've tried adding (create = true) to the inject, as well as trying injecting an EntityManager instead of a FullTextEntityManager, but no luck.  Any help would be appreciated.


      Here's my component:



      @Startup
      @Name("personSearchInit")
      @Scope(ScopeType.APPLICATION)
      public class PersonSearchInit {
      
           @In
           private FullTextEntityManager entityManager;
      
           @PostConstruct
           public void indexPerson() {
                final List<Person> people = entityManager.createQuery("SELECT p FROM Person p").getResultList();
      
                for (Person p : people) {
                     entityManager.index(p);
                }
           }
      }



        • 1. Re: EntityManagers in Application-scoped Startup components
          samdoyle

          If you do that on startup you will block the application server from starting up until completed which I'm pretty sure you don't want to do.


          What you can do is make your indexPerson @Asynchronous then from another component you can use @Observer or in your components.xml event for
          org.jboss.seam.postInitialization then call your method.
          Your entityManager should be injected successfully at that point.


          • 2. Re: EntityManagers in Application-scoped Startup components
            vinitadhopia

            That did it!  Thanks for the tip.  For anyone curious, here's the working code:



            @Name("personSearchInit")
            @Scope(ScopeType.APPLICATION)
            public class PersonSearchInit {
            
                 @In
                 private FullTextEntityManager entityManager;
            
                 @Asynchronous
                 @Observer("org.jboss.seam.postInitialization")
                 public void indexPerson() {
                      final List<Person> people = entityManager.createQuery("SELECT p FROM Person p").getResultList();
            
                      for (Person p : people) {
                           entityManager.index(p);
                      }
                 }
            }