Spring Hibernate SessionFactory

DD. picture DD. · Nov 14, 2011 · Viewed 49.6k times · Source

How do you create a SessionFactory using the java config?

@Bean
public SessionFactory sessionFactory(){
    AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
    sessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
    return sessionFactoryBean.getObject();
}

This doesnt work for some reason...it always returns null.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Nov 14, 2011

Return factory instead:

@Bean
public AbstractSessionFactoryBean sessionFactoryBean(){
    AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
    sessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
    return sessionFactoryBean;
}

If you need to inject SessionFactory directly somewhere in code, add this helper method:

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

Note that the helper sessionFactory() is not annotated with @Bean - this is really important.