hibernate 与spring 整合

至于spring 和hibernate 的整合的主要目的是 为了让spring 管理hibernate 的session 和事务


1.spring 对各种数据库都有很好的支持 没用spring 之前 如用hibernate 我们就会创建连接工厂类 现在我们用了spring 后
可以在xml 配置sessionfactory <bean id="sessionfactory2" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
</bean> 里面挤可以加载我们手工配置的 datasource(数据库连接)  可以加载我们用配置文件加载的对数据库的连接get


2. 如果我么你使用getcurentsession 我们需要在hibernate 的配置文档里加载一个东西
  hibernate3        <property name="hibernate.current_session_context_class">thread</property><!-- thread指本地事务 jdbc 用getcurrentsession创建session的对象的时候用到 -->
  hibernate4对spring 有了很好的支持了 <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>
  次前提是必须引入hibernate 和spring 的文件


3.用spring 控制hibernate 的事务  我们以getcurrentsession 为列子
  1. 首先在hibernatxml 配置文件中加载一个开启getcurrrentsesson 的配置 (如果是opensession 就不需要)
        <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>
2. 在对数据库的操作dao 层定一个属性sessionfactory 因为spring 对数据库的有很好的支持 
         <bean id="sessionfactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
             <property name="configLocation">
             <value>classpath:hibernate.cfg.xml</value>
             </property>
             </bean> 
3. 先配置事务管理器  其事务管理器必须加载datasource  此事务管理器管理session 的开启和关闭 事务的开启提交和回滚
          <bean id="transactionmanger" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
             <property name="dataSource" ref="datasourc"></property><!-- 事务管理器 必须加载 datasource -->
             <property name="sessionFactory" ref="sessionfactory"></property>  <!-- spring 的事务管理 加载此文件的 show_sql 映射文件等等属性-->
             </bean>


4.配置事务的特性(属性)包括事务的回滚 超市 只读  
     <tx:advice id="tx" transaction-manager="transactionmanger"><!--肯定要知道管理是谁的事务--〉
             <tx:attributes>
             <tx:method name="*save" propagation="REQUIRED" /><!-- 以save 结尾 -->
             </tx:attributes>
             </tx:advice>


5.最终 我们用aop 的思想 去管理事务  配置切点 (这个切点一般都是对数据库有最终交互的那一层)
                       <aop:config>
             <aop:pointcut expression="execution(* com.sht.Dao.*.*(..))" id="point"/> <!-- 切入点 -->
             <aop:advisor advice-ref="tx" pointcut-ref="point"/><!-- 每到这个切点 就执行这个事务管理特性 -->
             </aop:config>
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值