spring整合mybatis以及配置事務


提前說明:

  整合目的:使mybatis支持事務代理

  需要做的工作:

    1、將mybatis對象的創建交由spring

      ①配置第三方帶有連接池的數據源

      ②spring創建sqlsession對象

      ③mybatis通過映射接口創建對象,spring不支持通過接口創建對象,需要給出解決方案(在整合包)

    2、配置事務

      ①配置事務管理器

      ②配置通知

      ③使用AOP切入

具體步驟:

  1、配置數據源

<!-- 配置數據源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/sms"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

  2、配置會話工廠,用於創建sqlsession

    說明,只要配置了會話工廠,即可獲得sqlsession對象(看源碼)

<!--配置會話工廠  -->
    <bean name="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據源,用於創建sqlsession -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

  3、配置映射接口掃描包,創建mapper對象

<!-- 配置映射接口掃描包,用於創建mapper對象 -->
    <bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="my"></property>
      <!--指定會話工廠--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property> </bean>

  4、配置事務管理器

<!-- 配置事務管理器 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

  5、配置通知

<!-- 配置通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="select*" read-only="true" />
            <tx:method name="find*" read-only="true"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="*" read-only="false"/>
        </tx:attributes>
    </tx:advice>

  6、AOP切入

<!--AOP切入  -->
    <aop:config>
        <!--切入點  -->
        <aop:pointcut expression="execution(* my.service..*.*(..))" id="pc"/>
        <!-- 配置切面 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pc" />
    </aop:config>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM