我收到了一個帶有以下代碼和配置的NullPointerException
,我不知道爲什麼。我希望在調試這個問題時有所幫助。JPA EntityManager沒有被注入到Java EE應用程序中
文件的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 @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實現:
public class AdDaoImpl implements AdDao{
@PersistenceContext
public EntityManager entityManager;
@Override
public void save(Ad ad){
entityManager.persist(ad);
}
}
當我運行下面的JSP代碼,我得到NullPointerException異常
Ad ad = new Ad();
ad.setAdId(1000);
ad.setAdTitle("JPA pure");
AdDao newDao = new AdDaoImpl();
newDao.save(ad);
你在哪裏注射它? – uaiHebert 2014-10-07 22:36:59
剛剛編輯的問題,我注入它像@PersistenceContext公共EntityManager entityManager; – 2014-10-07 22:39:02
不知道:S第一次這樣做 – 2014-10-07 22:44:31