Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically create SessionFactory in Spring

Suppose I programmatically create a AnnotationSessionFactoryBean and set the various properties correctly. How can I then extract the Hibernate SessionFactory, since all methods that pertain to creating the SessionFactory are protected?

AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
SessionFactory sessionFactory = sessionFactoryBean.newSessionFactory(); // Protected!!
like image 580
chris Avatar asked Jan 21 '26 19:01

chris


1 Answers

Use getObject(), after calling afterPropertiesSet():

sessionFactoryBean.afterPropertiesSet();
SessionFactory sessionFactory = sessionFactoryBean.getObject();

(AnnotationSessionFactoryBean implements FactoryBean<SessionFactory>)

Be careful, though: by doing this, it becomes your responsibility to make sure the SessionFactory is closed when you're finished with it.

like image 112
skaffman Avatar answered Jan 23 '26 13:01

skaffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!