简体   繁体   中英

JPA EntityManager not being injected in Java EE app

I am receiving a NullPointerException 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" >
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.adism.domain.Ad</class>
    <properties>
        <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="" />
    </properties>

</persistence-unit>

Entity Class:

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

    public Ad(){}

    @Id
    @Column(name="adid")
    @GeneratedValue
    public Integer getAdId(){
        return adId;
    }


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

    @Column(name="adtitle")
    public String getAdTitle(){
        return this.adTitle;
    }

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

}

DAO Implementation:

public class AdDaoImpl implements AdDao{

  @PersistenceContext   
  public EntityManager entityManager;

  @Override   
  public void save(Ad ad){
     entityManager.persist(ad);   
   }

}

When I run following code in JSP, I get NullPointerException

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

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:

@Stateless
public class AdDao () {}

And you will use it in your servlet like:

@EJB
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();
    entityManager.getTransaction().begin();
    // do your stuff here
    entityManager.getTransaction().commit();
    entityManager.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM