EntityManager injection - NullPointerException

13,414

You can't access the EntityManager within the constructor. Take a look at the @PostConstruct-Annotation

@Service(value="inboxQueryBuilder")
public class InboxQueryBuilder {

@PersistenceContext
EntityManager em;

CriteriaBuilder cb;

public InboxQueryBuilder() {
    // em= null
}

@PostConstruct
public void toSomething(){
    // em set by Container  
    cb = em.getCriteriaBuilder();
}


public TypedQuery<App> getQueryForApps(AppSearchObject aso) {
       ...
}

...
}

EDIT: After reading your post again, I start to became unsure, if I'm right. I know the Java EE-Dependency-Injection within a JBoss works as I described, but I'm not sure about spring-IOC.

Share:
13,414
John Manak
Author by

John Manak

Updated on June 04, 2022

Comments

  • John Manak
    John Manak almost 2 years

    In my Spring+JPA/Hibernate+Wicket app, I have a QueryBuilder bean that I want to use in one of my DAOs which generates a typed query with the help of Criteria API:

    @Service(value="inboxQueryBuilder")
    public class InboxQueryBuilder {
    
        @PersistenceContext
        EntityManager em;
    
        CriteriaBuilder cb;
    
        public InboxQueryBuilder() {
            cb = em.getCriteriaBuilder();
        }
    
        public TypedQuery<App> getQueryForApps(AppSearchObject aso) {
               ...
        }
    
        ...
    }
    

    However, when I run the app, I get a null pointer exception for line:

    cb = em.getCriteriaBuilder();
    

    i.e. the EntityManager doesn't get injected. Do you know why?

    Also, is this use correct and thread-safe or should I instantiate my InboxQueryBuilder for each query? In that case, should I also inject the EntityManager or should I just pass it as a constructor parameter (the InboxQueryBuilder would get instantiated for each query in the DAO which has an injected instance of EntityManager)?

  • John Manak
    John Manak over 13 years
    yes i do. entitymanager gets injected into the DAO that calls getQueryForApps method without a problem.
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    OK, do you have autowiring turned on?
  • nanda
    nanda over 13 years
    then the comment from seanizer is the answer. You should make it spring singleton
  • Michael Wiles
    Michael Wiles over 13 years
    This is where spring is your friend! It is doing the autowire of the entity manager for you - without spring this would not work - the auto injection of the Entity Manager only works (via the Application Server) if you're running inside an EJB.