我正在尝试将EntityManager注入我的Tomcat 7应用程序。
我有一个管理我的查询的类(service.PresentatieDao),我有这个代码:
private EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
在我的applicationContext.xml中,我有这一行:
<bean name = "presentatieDao" class="service.PresentatieDao"/>
最后在我的dispatcher-servlet.xml中我有这段代码(复制粘贴,编辑指向正确):
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/Project2-DB"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>domein</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL"/>
</bean>
</property>
</bean>
<bean id="transactionManager"
class=" org.springframework.orm.jpa.JpaTransactionManager ">
<constructor-arg ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
在我的控制器中:
@Autowired
private PresentatieDao presentatieDao;
我已经解决了关于我的映射的所有类型的错误,我已经解决了。
现在我在PresentatieDao的这一行得到一个NullPointerException:
return em.createQuery("select p from Presentatie p").getResultList();
在这种情况下,em是null
。任何想法在这里可能有什么问题?
答案 0 :(得分:1)
好的,我查看了Spring docummentation.It应该像这样工作
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" />
<bean name = "presentatieDao" class="service.PresentatieDaoImpl"/>
<bean class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
和
public class PresentatieDaoImpl implements PresentatieDao {
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this. entityManager = entityManager;
}
public Collection loadProductsByCategory(String category) {
return entityManager.createQuery("from Product p where p.category = :category")
.setParameter("category", category).getResultList();
}
}
了解更多信息:
https://spring.io/blog/2006/08/07/using-jpa-in-spring-without-referencing-spring
您还可以查看:
http://doanduyhai.wordpress.com/2011/11/21/spring-persistencecontext-explained/