0

Its the First time i am integrating spring with hibernate, When i invoke any method of Dao class i am getting null pointer Exception

I am using abstract factory pattern Source code of Abstract class :

public abstract  class Content {

    @Autowired
    HibernateOperations ho;

    @Transactional
    public List<ContentDes> getContentDes(String sql,int limit){

        //do it with autowired


        List<Object[]> ls  = new ArrayList<Object[]>();
        List<ContentDes> contentDes_ls  = new ArrayList<ContentDes>();

        System.out.println("--before invoking method---");
        ho.just_print();

        ls = ho.getResultListByLimit(sql,limit);


         for(Object[] obj: ls){
               ContentDes contentDes = new ContentDes();
                 contentDes.setCode((String)obj[0]);
                 contentDes.setContent_prv((String)obj[1]);
                 contentDes.setPricetag((String)obj[2]);
                 contentDes_ls.add(contentDes);
          }
         return contentDes_ls;

    }

    abstract List<ContentDes> getRandomContent(int limit);
    //abstract List<ContentDes> getDistinctCat();

}

And i have five class that are extending my Content Class: coding of one of my child id liem below:

public class Wallpaper extends Content{



    @Override
    public  List<ContentDes> getRandomContent(int limit) {
          String sql  = "select code,prv,pricetag from Wallpaper where cat not like 'Holy Deities'  order by rand() limit "+limit+"";
          List<ContentDes> contentDes_ls  = new ArrayList<ContentDes>();
          contentDes_ls =  getContentDes(sql,limit);
        return contentDes_ls;
     }


} 

And class which returning clasess obects according to the content type is :

public class GetContentFactory {

    //use getContent method to get object of type Content   
    public Content getContent(String contentType) {
        contentType = contentType.toLowerCase();

        if (contentType.equalsIgnoreCase("wallpaper")) {

            return new Wallpaper();
        } else if (contentType.equalsIgnoreCase("animation")) {

            return new Animation();
        } else if (contentType.equalsIgnoreCase("ringtone")) {

            return new Ringtone();
        } else if (contentType.equalsIgnoreCase("video")) {

            return new Video();
        } 
        else if (contentType.equalsIgnoreCase("game")) {

            return new Game();
        }
        else {
            System.out.println(" unknow request  in GetContentFactory class");
}
        return null;
    }
}//end of GetContentFactory class.

My main class is :

public class GetContent {

    GetContentFactory contentFactory = new GetContentFactory();


    }

     public List<ContentDes> getRandomContent(String content_type, int limit) {
         List<ContentDes> contentDes_ls  = new ArrayList<ContentDes>();
        Content con = contentFactory.getContent(content_type);
       contentDes_ls = con.getRandomContent(limit);
       for (ContentDes contentDes : contentDes_ls) {
           System.out.println("prv----"+contentDes.getContent_prv());

    }

        return contentDes_ls;
    }


}

Code of my dao class is :

@Repository
public class HibernateOperations {
    private SessionFactory sessionFactory;


    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    //pass the sql query to get result for multiple column  
    public List<Object[]> getResultListByLimit(String query,int limit){

        System.out.println("in get result-------");

            Session session = this.sessionFactory.getCurrentSession();
            List<Object[]> ls_ob = new ArrayList<Object[]>();
            Query q = session.createQuery(query);
             q.setMaxResults(limit);
            ls_ob  = (List<Object[]>)q.list();
            return ls_ob;

}


 public List<Object> getListForSingleColumn(String query){
        Session session = this.sessionFactory.getCurrentSession();
          List<Object> ls_ob = new ArrayList<Object>();
            Query q = session.createQuery(query);
            ls_ob  = q.list();
            return ls_ob;
        }

    public void SaveObject(Object obj){

        Session session = this.sessionFactory.getCurrentSession();
        List<Object[]> ls_ob = new ArrayList<Object[]>();
        session.save(obj);
      }


    public void just_print(){
        System.out.println("---------in method hibenate operation------");
    }

}

when My controller class methods call:

GetContent gc = new GetContent();

    List<ContentDes> contentDes_ls  = new ArrayList<ContentDes>();
    contentDes_ls  = gc.getRandomContent("wallpaper", 3);

i got an exception:

its prints the

--before invoking method---(its is the sout of my content class method Name "getContentDes")

Apr 25, 2016 6:03:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DefaultServlet] in context with path [/slwap_sh] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at lanka.content.get.Content.getContentDes(Content.java:37)
    at lanka.content.get.Wallpaper.getRandomContent(Wallpaper.java:45)
    at lanka.content.controller.ContentController.sriWap(ContentController.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

I am unable to call any of my Dao Class methods i got null pointer when i called any method of my Dao(HibernateOperations.java) Class

Can anyone please help me to find out my mistake

coding of DefaultServlet-servlet.xml is like below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">


    <mvc:annotation-driven />
    <mvc:annotation-driven enable-matrix-variables="true" />
    <context:component-scan base-package="lanka.content.controller" />
    <context:component-scan base-package="lanka.content.domain" />
    <context:component-scan base-package="lanka.content.utility" />

     <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

<!-- start of languages xml code -->


<!-- lang param is defined in the mvc interceptor -->

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="WEB-INF/propFiles/content" />
        <property name="defaultEncoding" value="UTF-8" />

    </bean> 

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en" />

    </bean>


    <!-- end of languages xml code -->

    <mvc:interceptors>
        <mvc:interceptor>
             <mvc:mapping path="/**" /> 

        <bean
            class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="lang" />
        </bean>
        </mvc:interceptor>




        <!-- <mvc:interceptor>
            <mvc:mapping path="/**" />
            <mvc:exclude-mapping path="/resources/**"/>
             <bean id="storingWapHits"
                class="vodafone.interceptor.StroringHits">

            </bean>
        </mvc:interceptor> -->

        </mvc:interceptors> 

    <mvc:resources mapping="/resources/**" location="/resources/design/" />

<!-- start of hibernate integration -->


    <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/wapsite" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>


<!-- hibernate4AnnotatedSessionFactory is a session fectory-->
    <!-- Hibernate 4 SessionFactory Bean definition -->
    <bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>

                <value>lanka.content.table.Game</value>
                <value>lanka.content.table.Scrsaver</value>
                <value>lanka.content.table.Video</value>
                <value>lanka.content.table.Wallpaper</value>



            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

<tx:annotation-driven transaction-manager="transactionManager" />


    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>

    <!-- <bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
        <property name="personDAO" ref="personDAO"></property>
    </bean>-->


        <bean id="HibernateOperations" class="lanka.content.utility.HibernateOperations">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean> 




</beans>
Kunal Batra
  • 821
  • 3
  • 14
  • 35
  • you have `@Autowired` for `HibernateOperations` class with reference name ho in `Content` class. But bean id is not present in bean.xml file. Add `@Qualifier("HibernateOperations")` after `@Autowired` annotation. – Channa Jayamuni Apr 25 '16 at 13:10

1 Answers1

1

By doing :

new Wallpaper();

You are not letting spring do his work, that is to say inject things in your objects :

@Autowired
HibernateOperations ho;

ho will always be null.

Every Content subclasses should be spring beans, and you have to get rid of your GetContentFactory, and only autowire every single spring bean

EDIT : Abstract Factory Design

Define your beans like this :

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Wallpaper extends Content {

Declare the GetContentFactory as a spring bean as well :

@Component
public class GetContentFactory {

  @Autowired
  private Wallpaper wallpaper;

This has to be avoided as well :

GetContentFactory contentFactory = new GetContentFactory();
Pras
  • 1,068
  • 7
  • 18