Announcement Announcement Module
Collapse
No announcement yet.
Unable to inject entityManagerFactory / NullPointerException Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Unable to inject entityManagerFactory / NullPointerException

    hi,

    since 3 days i'm trying to inject a EntityManager or EntityManagerFactory into my Dao to access the DB.
    But the field is always null... and i have no idea whats the problem.
    I tried it with @Autowired, with normal beans, and so on...

    here's the current code from my applicationContext.xml:

    Code:
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <property name="showSql" value="true" />
                    <property name="generateDdl" value="true" />
                    <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
                </bean>
            </property>
            <property name="persistenceUnitName" value="MontyBroganPU" />
            <property name="dataSource" ref="dataSource" />
    
        </bean>
    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/MontyBrogan"/>
            <property name="username" value="root"/>
            <property name="password" value="ganzgeheim"/>
        </bean>
    
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory"></property>
            <property name="dataSource" ref="dataSource"/>
        </bean>
            
        <tx:annotation-driven />
        <context:annotation-config/>
        <context:component-scan base-package="DaoImpl"/>
        
        <!-- <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> -->
         <!-- <bean id="lectureDao" class="DaoImpl.LectureDaoImpl" /> -->
    and my LectureDaoImpl:
    Code:
    @Repository
    public class LectureDaoImpl implements LectureDao {
    
        
        private EntityManagerFactory entityManagerFactory;
    
        @Autowired
        @PersistenceUnit(unitName = "MontyBroganPU")
        public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
            this.entityManagerFactory = entityManagerFactory;
        }
    
    @Transactional(readOnly = true)
        public List<Lecture> findAll() {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            Query query = entityManager.createQuery("from Lecture");
            return query.getResultList();
        }
    my persistence.xml has just the header
    Code:
    <?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="MontyBroganPU">
      </persistence-unit>
    </persistence>
    and the error:
    Code:
    09:39:33,339 ERROR [DispatcherPortlet:501] Could not complete request
    java.lang.NullPointerException
            at DaoImpl.LectureDaoImpl.findAll(LectureDaoImpl.java:53)
            at Controller.ViewController.handleRenderRequestInternal(ViewController.java:44)
            at org.springframework.web.portlet.mvc.AbstractController.handleRenderRequest(AbstractController.java:219)
            at org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter.handleRender(SimpleControllerHandlerAdapter.java:52)
            at org.springframework.web.portlet.DispatcherPortlet.doRenderService(DispatcherPortlet.java:811)
    please help me

  • #2
    Have you tried setting it explicitly rather than component-scan and autowired? Your component-scan does look strange, normally it should take in the base package for example com.xyz.app.function.

    Try setting it explicitly in the application context and then see if it is injected.

    Comment


    • #3
      yes i tried it with:
      Code:
       <bean class="DaoImpl.LectureDaoImpl">  
               <property  name="entityManagerFactory" ref="entityManagerFactory" />  
           </bean>
      and the <bean class="org.springframework.orm.jpa.support.Persist enceAnnotationBeanPostProcessor" />
      but this doesnt inject the factory... or it injects it and something changes the factory to null...

      what do you mean looks strange? im absolutly new to spring so any help/hint is appreciated

      Comment


      • #4
        i could also upload the .war file if this may help...?

        Comment


        • #5
          in your controller class are you injecting to interface or directly to dao.
          if you inject into dao it is normal, you must inject to interface.

          Comment


          • #6
            sorry i dont understand what you mean...
            so maybe its the best i just paste the code:
            Code:
            @Controller
            public class ViewController extends AbstractController {
            
                LectureDaoImpl data = new LectureDaoImpl();
                public ViewController() {
                }
            
                protected ModelAndView handleRequestInternal(
                        HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
                    
                    ModelAndView modelAndView = new ModelAndView("View");
                    modelAndView.addObject("message", "hello from handleRequestInternal() in ViewController");
                    
                    return modelAndView;
            
                }
            
                @Override
                protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response)
                        throws Exception {
                    ModelAndView modelAndView = new ModelAndView("View");
                    List<Lecture> lectures = data.findAll();
                    modelAndView.addObject("lectures", lectures);
                    modelAndView.addObject("message", "hello from handleRenderRequestInernal() in ViewController");
                    return modelAndView;
                }
            }
            i just call findAll() from my Dao and this returns the NullpointerException because entityManagerFactory is null

            Comment


            • #7
              Code:
              LectureDaoImpl data = new LectureDaoImpl();
                  public ViewController() {
                  }
              if I am not wrong here is your problem, you are doing an instance from a class, and spring works injecting dependency, you have to do something like this:
              Code:
              private LectureDaoInterface lectureInterface;
              
              public void LectureDaoInterface (LectureDaoInterfacelectureInterface){
              		this.lectureInterface= lectureInterface;
              	}
                  public ViewController() {
                  }

              Comment


              • #8
                Yep. You didn't show us the controller class which was using the dao. You need Spring to inject the dao into the controller as Spring will give you a fully configured class. By creating a new instance of the dao in your controller you effectively have an incomplete class with no dependencies injected.

                If you follow duardito's advice it should work.

                Comment


                • #9
                  Ok so i understand that the new LectureDaoImpl() was a problem and thats clear.
                  My interface for the dao is called LectureDao and the implentation LectureDaoImpl.

                  i changed the ViewController.java to this now:
                  Code:
                  @Controller
                  public class ViewController extends AbstractController {
                      private LectureDao lectureDao;
                  
                      public ViewController() {
                      }...
                  and applicationContext:
                  Code:
                   <bean id="viewController" class="Controller.ViewController" >
                          <property name="lectureDao" ref="lectureDao" />
                      </bean>
                  
                      <bean id="lectureDao" class="Dao.LectureDao">
                          <property name="entityManagerFactory" ref="entityManagerFactory"/>
                      </bean>
                  but i still receive the NullPointerException...

                  i uploaded the archive (as .tar.bz2) so if someone wants to take a look at it..
                  http://217.172.187.219/MontyBrogan.tar.bz2
                  i can also upload it as zip if someone needs it...

                  thanks for helping

                  Comment


                  • #10
                    Don;t you want your dao definition to be :

                    Code:
                     <bean id="lectureDao" class="Dao.LectureDaoImpl">
                            <property name="entityManagerFactory" ref="entityManagerFactory"/>
                        </bean>
                    Considering the LectureDao is the interface. So then your controller definition should be:

                    Code:
                     <bean id="viewController" class="Controller.ViewController" >
                            <property name="lectureDao" ref="lectureDao" />
                        </bean>
                    HTH

                    Comment


                    • #11
                      yes i have it now to the class and not the interface... im working the whole day on this so i change always something to check if it may work because i'm running into some pressure of time - the injection to the interface was just a test (i thought maybe this is working with entityManagerFactory in the interface).

                      still no luck...

                      Comment


                      • #12
                        its working now
                        i removed the beanpostprocessor and all annotations from LectureDaoImpl...
                        now the lectureDao in my controller is null... i hope i can fix this

                        thx for your help

                        Comment

                        Working...
                        X