栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Hibernate事务管理

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Hibernate事务管理

您的问题中有些事情还不清楚。我的解释基于以下假设-

  • 您正在使用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声明式事务



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506955.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号