Fixing Null EntityManger in Spring MVC application?

后端 未结 4 1763
逝去的感伤
逝去的感伤 2020-12-09 06:49

In the following code I am trouble with my injected EnitityManager, which always shows up as null;

public class GenericController extends Ab         


        
相关标签:
4条回答
  • 2020-12-09 06:59

    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.

    0 讨论(0)
  • 2020-12-09 07:08

    Have you included

    <context:annotation-config />
    

    In your spring XML. Reference here

    0 讨论(0)
  • 2020-12-09 07:12

    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.

    0 讨论(0)
  • 2020-12-09 07:19

    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.

    0 讨论(0)
提交回复
热议问题