修复Spring MVC应用程序中的Null EntityManger?

在下面的代码中,我注入了EnitityManager,它总是显示为null ;

public class GenericController extends AbstractController { @PersistenceContext(unitName = "GenericPU") private EntityManager em; protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { //(em == null) is always trigged if (em == null) throw new NullPointerException("em is null"); Collection Generics = em.createNamedQuery("Generic.findAll").getResultList(); ModelAndView mav = new ModelAndView("Generic"); mav.addObject(Generics); return mav; } } 

这是bean定义,在dispatcher-servlet.xml中定义。

  

应该在persistence-context.xml文件中定义基于tx:annotation的注入EnitityManager。

                             

持久性上下文是从applicationContext.xml加载的

     

完成类路径导入是因为ORM实体作为JAR文件包含在项目中。 请注意,我相信正在加载持久性上下文,因为如果无法解析其配置文件,Spring将不允许部署该应用程序。

这是我的persistence.xml

    com.application.orm.jpa.Generic    

还有我的web.xml

    contextConfigLocation /WEB-INF/applicationContext.xml   org.springframework.web.context.ContextLoaderListener   dispatcher org.springframework.web.servlet.DispatcherServlet 2   dispatcher *.htm    30    redirect.jsp   

有人可以帮我从这里出去吗?

今天我很幸运能够和一位顾问谈论这个问题,他能够帮我整理一切。

所以我的问题是Spring MVC正在建立两个不同的上下文 ,一个在applicationContext.xml中定义的应用程序上下文和一个在dispatcher-servlet.xml中定义的web上下文。

来自一个上下文的Bean无法在另一个上下文中与bean通信,因此当我在applicationContext.xml中启动我的持久化上下文时,我无法在由dispatcher-servlet.xml(即我的控制器)加载的bean中访问它。

当Netbeans自动生成我的Spring MVC的基础时,它默认设置它。 在一些大型Web应用程序中,将应用程序的Web部分与其他逻辑(持久性,业务代码等)区分开来是有意义的。 在我的情况下,我试图将我的实体经理直接自动注入我的控制器,这对我不利。

为了解决这个问题,我移动了这条线

  

从applicationContext.xml到我的dispatcher-servlet.xml。 然后我的控制器从@PersistanceContext注释中正确地注入了EntityManagers。

我认为你需要一个文件persistence.xml

    com.domain.MyClass   

我认为如果文件具有不同的名称将无法工作,尤其是因为您没有告诉EntityManager工厂任何地方的新名称。

我曾经使用过较旧的spring版本,当你必须将setProperty()放到bean中并在spring-bean定义中设置propery标签时:

    

也许您应该使用transactionManager或entityManagerFactory bean …

PD:我个人更喜欢旧的注入依赖关系的方式。

你有没有

  

在你的springXML。 参考这里