I am trying to move a spring3.2.x + hibernate4.x setup from a xml to java configuration.
Heres a snippet of the existing code:
import org.hibernate.SessionFactory;
import org.hibernate.Query;
import org.hibernate.Session;
public class StockDaoImpl implements StockDao{
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void save(Stock stock){
Session session = getSessionFactory().openSession();
try{
session.save(stock);
}
finally{
session.close();
}
}
The spring config file
<!-- Stock Data Access Object -->
<bean id="stockDao" class="com.data.dao.StockDaoImpl" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="dataSource">
.....
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
......
</property>
<property name="mappingResources">
.......
</property>
</bean>
This works fine - but how do i re-define this config in java?
Heres an attempt -
@Bean
public StockDao stockDao() {
StockDaoImpl dao=new StockDaoImpl();
dao.setSessionFactory(sessionFactory());
return dao;
}
......
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { .....});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
But this wont compile as the sessionFactory
being referred to is not Spring's LocalSessionFactoryBean?
How do I reconcile this?
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();
}
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