EntityManager injection - NullPointerException

一笑奈何 提交于 2019-12-03 08:43:36
Christian Kuetbach

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.

Do you have this bean somewhere in your application context?

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
  <property name="persistenceUnitName" value="myPersistenceUnit"/>
</bean>

Spring uses the Java Beans mechanism, so I am pretty sure this is insufficient:

@PersistenceContext
EntityManager em;

Here's the standard way:

private EntityManager entityManager;

@PersistenceContext
public void setEntityManager(final EntityManager entityManager){
    this.entityManager = entityManager;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!