Hibernate SessionFactory vs Spring LocalSessionFactoryBean

LocalSessionFactoryBean is a FactoryBean<SessionFactory>. It means that it allows creating instances of SessionFactory.

So you just need

public StockDao stockDao() {
    StockDaoImpl dao=new StockDaoImpl();
    dao.setSessionFactory(sessionFactory().getObject());
    return dao;
}

But I wouldn't create DAOs explicitel like that. Simply annotate your DAO with @Repository, and autowire the session factory using @Autowired. Make sure the Java config class is annotated with @ComponentScan("the.base.package.of.daos")


Missing getObject() call in return.
Substituite with return sessionFactory.getObject() (and change return type,too!)


JB Nizet's answer helped me, but I needed to declare the beans separately for it to work:

@Bean
public LocalSessionFactoryBean sessionFactoryBean(final DataSource dataSource,
                                              final Properties hibernateProperties,
                                              final List<String> hibernateMappings) {
    LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource);
    sessionFactoryBean.setHibernateProperties(hibernateProperties);
    sessionFactoryBean.setMappingResources(hibernateMappings.toArray(new String[hibernateMappings.size()]));
    return sessionFactoryBean;
}

@Bean
public SessionFactory sessionFactory(LocalSessionFactoryBean sessionFactoryBean) {
    return sessionFactoryBean.getObject();
}