简体   繁体   中英

SessionFactory not initialized

i created a DAO (ForecastPersistorDao.java) which is the interface and its corresponding implementation (ForecastPersistorDaoImpl.java). The implementation has a method 'persist()' whose job is to persist some data into the database. When I try to call persist to persist the data, it throws a NullPointerException since it does not initialize SessionFactory properly. Please help me point out what I might be doing wrong:

ForecastPersistorDao.java

public interface ForecastPersistorDao {

    void persist(List<ForecastedDemand> forecastedDemands);
    List<DemandForecast> retrieveLastForecast(String marketplaceId);

}

ForecastPersistorDaoImpl.java

@Repository("forecastPersistorDao")
public class ForecastPersistorDaoImpl implements ForecastPersistorDao {

    private SessionFactory sessionFactory;

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

    /**
     * Persist forecast in the database for later
     * 
     * @param forecastedDemands
     *            List of forecast for all asin:marketplaceId tuple
     */
    @Transactional
    @Override
    public void persist(List<ForecastedDemand> forecastedDemands) {
        System.out.println("THIS IS ALWAYS NULL-------->>>>>>>> " + sessionFactory);
        Session session = sessionFactory.getCurrentSession();
        Date forecastCalculationDate = new Date();

        // For each [asin:marketplace] tuple
        for (ForecastedDemand forecastedDemand : forecastedDemands) {
            String asin = forecastedDemand.getAsinMarketplaceId().getAsin();
            String marketplaceId = forecastedDemand.getAsinMarketplaceId().getMarketplaceId();
            String forecastingModel = forecastedDemand.getForecastingModel();
            SortedMap<Instant, Double> forecast = forecastedDemand.getForecast();

            // for each forecast date - write an entry in demand_forecasts table
            for (Map.Entry<Instant, Double> entry : forecast.entrySet()) {
                Date dateOfForecast = entry.getKey().toDate();
                double quantityForecasted = entry.getValue();
                DemandForecast forecastToPersist = new DemandForecast(asin, marketplaceId, forecastCalculationDate,
                        forecastingModel, quantityForecasted, dateOfForecast);
                session.save(forecastToPersist);
            }
        }
    }

Main class (Runner.java):

public final class FbsRunner {
    private ForecastPersistorDao forecastPersistorDao;

    public static void main(String[] args) {
        Runner runner = new Runner();
        runner.run();
    }

    public void run() {
        ApplicationContext context =
                new FileSystemXmlApplicationContext("spring-configuration/application-config.xml");
        forecastPersistorDao = (ForecastPersistorDao) context.getBean("forecastPersistorDao"); // this works fine

        System.out.println(">>>>>>>>>> forecastPersistorDao [this is fine (not null)]: " + forecastPersistorDao);

        List<ForecastedDemand> forecastedDemand = [a list of Forecasted demand to be persisted int he DB]
        // THE CALL BELOW FAILS...
        forecastPersistorDao.persist(forecastedDemands);
        System.out.println("Persisted demand in the database"); // We don't reach here.
    }
}

spring-configuration/application-config.xml

<?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:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    ">

    <!--  The main application context spring configuration -->
    <import resource="application/hibernate.xml" />
    <import resource="common/hibernate.xml" />

    <!--<import resource="application/proxies.xml" />-->
    <!--<import resource="common/aggregators.xml" /> -->
    <import resource="application/environment.xml" />
    <!--
        Add any beans specific to your application here
    -->
    <bean id="forecastPersistorDao" class="com.amazon.fresh.fbs.dao.ForecastPersistorDaoImpl" />

</beans>

application/hibernate.xml:

<bean id="SessionFactory"
          class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
          parent="AbstractSessionFactory" depends-on="EnvironmentHelper" >
        <property name="hibernateProperties">
...
...
everything as expected
...
</bean>

common/hibernate.xml:

<beans ... >
bean id="AbstractSessionFactory"
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
            abstract="true">
        <property name="mappingResources">
            <list>
                <value>com/amazon/fresh/fbs/dao/hibernate/RtipData.hbm.xml</value>
                <value>com/amazon/fresh/fbs/dao/hibernate/Vendor.hbm.xml</value>
                <value>com/amazon/fresh/fbs/dao/hibernate/AdjustmentPeriod.hbm.xml</value>
                <value>com/amazon/fresh/fbs/dao/hibernate/DemandForecast.hbm.xml</value>
            </list>
        </property>
        <property name="exposeTransactionAwareSessionFactory">
            <value>true</value>
        </property>
     </bean>

     <!-- Use Spring transactions for Hibernate -->
     <tx:annotation-driven transaction-manager="txManager" mode='proxy' proxy-target-class='true'/> 

     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="SessionFactory" />
     </bean>

     <aop:aspectj-autoproxy/>
</beans>

Please try to add <context:component-scan base-package="YOUR PACKAGE NAME" /> into your application-config.xml . This will tell Spring to scan for annotated components that will be auto-registered as Spring beans.

"YOUR PACKAGE NAME" should be the package name to scan for annotated components.

sessionFactory没有正确自动装配,为ForecastPersistorDaoImpl添加“@component”并在application-config.xml中添加“context:component-scan”以告诉spring初始化。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM