A few things are not clear from your question. My explanation is based on the following assumptions:
- You use spring to create a data source and a factory session
- You are using Java 5 or higher and can use annotations.
Here is what your spring configuration looks like.
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver" /> <property name="url" value="jdbc:hsqldb:hsql://localhost:9001" /> <property name="username" value="sa" /> <property name="password" value="" /> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource" /> <property name="mappingResources"> <list> <value>product.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" />
Once this is set up, you can use spring transactional annotations for your DAO methods, as shown below. spring will take care of starting transactions, committing transactions, or discarding transactions when exceptions are thrown. If you have business services, ideally you would use transactional annotations for your services instead of DAOs.
@Transactional(propagation=Propagation.REQUIRED) public class MyTestDao extends HibernateDaoSupport { public void saveEntity(Entity entity){ getHibernateTemplate().save(entity); } @Transactional(readOnly=true) public Entity getEntity(Integer id){ return getHibernateTemplate().get(Entity.class, id); } }
The code below shows how transactions can be managed using spring support for AOP, not annotations.
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory" /> <bean id="testDao" class="com.xyz.daos.MyTestDao" /> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="allDaoMethods" expression="execution(* com.xyz.daos.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethods" /> </aop:config>
For more information, please, Spring Declarative Transactions
Sashi
source share