Tefa Tefa - 1 year ago 89
Java Question

JPA EntityManager not being injected in Java EE app

I am receiving a

with the following code and configuration, and I am not sure why. I would appreciate some help in debugging this issue.

File persistence.xml:

<persistence-unit name="adismPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/adism" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="" />


Entity Class:

@Entity @Table(name = "ads") public class Ad {
private Integer adId;
private String adTitle;

public Ad(){}

public Integer getAdId(){
return adId;

public void setAdId(Integer adId){
this.adId = adId;

public String getAdTitle(){
return this.adTitle;

public void setAdTitle(String title){
this.adTitle = title;


DAO Implementation:

public class AdDaoImpl implements AdDao{

public EntityManager entityManager;

public void save(Ad ad){


When I run following code in JSP, I get NullPointerException

Ad ad = new Ad();
ad.setAdTitle("JPA pure");
AdDao newDao = new AdDaoImpl();

Answer Source

If you just do AdDao newDao = new AdDaoImpl(); your container will not known where to inject the EntityManager.

If you are using JBoss or Glassfish (or someother kind of EJB Containner) you need to declare AdDao as EJB:

public class AdDao () {}

And you will use it in your servlet like:

public AdDao ejb;

PS.: I would not inject a DAO in a controller. The best is to use other classes between both, but if you are new to this kind of technology start with it.

If you are using a solution without JPA you can do something like: private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("YOUR_PERSISTENCE_UNIT"); // store it in your class

public void yourMethod(){
    final EntityManager entityManager = entityManagerFactory.createEntityManager();
    // do your stuff here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download