Fixing Null EntityManger in Spring MVC application?

孤街醉人 提交于 2019-11-28 07:48:59

I was lucky enough today to be able to speak with a consultant about this issue, he was able to help me sort the whole thing out.

So my problem is that Spring MVC was establishing two distinct contexts, one application context, defined in applicationContext.xml and one web context, defined in dispatcher-servlet.xml.

Beans from one context can not talk to beans in another context, thus when I initilized my persistence context inside of applicationContext.xml, I could not access it in beans loaded by dispatcher-servlet.xml, ie my controllers.

When Netbeans auto-generated the base to my Spring MVC it set this up by default. In some large web applications, it would make sense to separate the web part of the application in a context distinct from the rest of the logic (persistence, business code, etc). In my case, where I am trying to auto inject my entity manager directly into my controllers, this worked against me.

To fix the issue I moved the line

<import resource="classpath:META-INF/persistence-context.xml"/>

From the applicationContext.xml, to my dispatcher-servlet.xml. My controllers then were properly injected with EntityManagers from the @PersistanceContext annotation.

I think you need a file persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

  <persistence-unit name="GenericPU">
     <class>com.domain.MyClass</class>
  </persistence-unit>

</persistence>

I think it will not work if the file has a different name, especially not since you don't tell the EntityManager factory the new name anywhere.

I used to work with an older spring version, when you had to put setProperty() to the bean and set the propery tag inside the spring-bean definition like:

<bean id="Generic" class="com.application.web.GenericController" />
    <property name="em" ref="entityManager" />
</bean>

Maybe you should work with the transactionManager or the entityManagerFactory beans...

PD: I personally prefer the old way of injecting dependencies.

Have you included

<context:annotation-config />

In your spring XML. Reference here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!