Will I need to provide both a DataSource setter AND a SessionFactory setter in the outer class for the container to call? Or, is there an easy way to get a DataSource from a SessionFactory (or a SessionFactory from a DataSource)?
I think I answered my own question. From studying the API's a little more closely, I discovered org.springframework.orm.hibernate.SessionFactoryUt ils.getDataSource(). This allowed me to derive the DataSource from the SessionFactory so my DAO only needed a setter for SessionFactory. That was too easy...is there any downside to this technique????
If it's helpful to anyone else who wants to use some JDBC (for example, Spring's JDBC operation objects) inside their Hibernate DAO, here's an excerpt of my code:
Code:
package mypackage;
// various imports here...
public class HibernateLocationDao extends HibernateDaoSupport implements LocationDao
{
private LocationsQuery locationsQuery;
// overrides base class
protected void initDao() throws Exception
{
super.initDao();
// Here I get the DataSource from the SessionFactory so my DAO does NOT need a
// setDataSource() method. Note that setSessionFactory() is inherited from HibernateDaoSupport.
locationsQuery = new LocationsQuery(SessionFactoryUtils.getDataSource(getSessionFactory()));
}
public Collection getLocations() throws DataAccessException
{
return locationsQuery.execute();
}
public Collection getCountries() throws DataAccessException
{
return getHibernateTemplate().find("from Country country order by country.name");
}
public Country loadCountry(long id) throws DataAccessException
{
return (Country) getHibernateTemplate().load(Country.class, new Long(id));
}
public void saveCountry(Country country) throws DataAccessException
{
getHibernateTemplate().saveOrUpdate(country);
}
class LocationsQuery extends MappingSqlQuery {
private static final String LOCATIONS_SQL =
"SELECT blah blah blah...";
protected LocationsQuery(DataSource ds) {
super(ds, LOCATIONS_SQL);
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
Location location = new Location();
location.setId(rs.getLong("id"));
// other location setter calls here...
return location;
}
}
}
Here's the relevant part of my bean configuration file:
Code:
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>location.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.DB2Dialect</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="locationDao" class="com.cbconstantini.spring.locationapp.dao.HibernateLocationDao">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>