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.
SessionFactory is an Interface which is present in org. hibernate package and it is used to create Session Object. It is immutable and thread-safe in nature. buildSessionFactory() method gathers the meta-data which is in the cfg Object. From cfg object it takes the JDBC information and create a JDBC Connection.
The SessionFactory interface serves as factory for TopLink Sessions, allowing for dependency injection on thread-safe TopLink-based DAOs. Used by TopLinkAccessor/Template and TopLinkTransactionManager.
Hibernate SessionFactory is an interface. It can be created through providing objects of Configuration. This will contain all the database property details which are pulled from either hibernate. properties file or hibernate.
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.
Tomasz is right, but I do believe that creating object instance using "new" does not feet with Spring concept:
I think you need to do it this way:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.vanilla.objects.Student</value>
<value>com.vanilla.objects.Address</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
and then you can use it inside your Spring bean:
@Autowired
SessionFactory sessionFactory;
and then inside of your method:
Session session = sessionFactory.getCurrentSession();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With