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.
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.