您的问题中有些事情还不清楚。我的解释基于以下假设-
- 您正在使用spring创建数据源和会话工厂
- 您正在使用Java 5或更高版本,并且可以使用注释。
这是您的弹簧配置的外观。
<bean id="myDataSource" 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" > <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" > <property name="sessionFactory" ref="mySessionFactory" /></bean><tx:annotation-driven transaction-manager="transactionManager" />
设置完成后,您可以在DAO方法上使用spring事务注释,如下所示。当抛出异常时,Spring将负责启动事务,提交事务或回滚事务。如果您有商务服务,则理想情况下,应在服务上使用事务性注释,而不要使用DAO。
@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);} }下面的代码显示了如何使用spring对AOP的支持而不是注释来实现事务管理。
<!-- Define your 'myDatasource' bean and 'mySessionFactory' bean as shown in previous pre snippet --><!-- Then follow the steps shown below --><bean id="transactionManager"><property name="sessionFactory" ref="mySessionFactory" /><!-- this is the dao object that we want to make transactional --><bean id="testDao" /><!-- the transactional advice --><tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true" /> <!-- other methods use the default transaction settings (see below) --> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes></tx:advice><!-- ensure that the above transactional advice runs for any execution of a method in 'daos' package--><aop:config> <aop:pointcut id="allDaoMethods" expression="execution(* com.xyz.daos.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethods" /></aop:config>
有关更多详细信息,请参阅
-Spring声明式事务



