SSM框架下利用mybatis-spring.jar整合包,以及利用注解@transactional实现事务管理

来源:互联网 发布:非53端口dns 编辑:程序博客网 时间:2024/05/30 23:01

首先是准备jar包,利用mybatis-spring.jar整合包,就要取去下载一个名为mybatis-spring-1.3.1的jar包或其它版本的包,地址为https://github.com/mybatis/spring/releases

然后是需要对工程进行配置

首先是applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <!-- 加载db.properties文件中的内容,db.properties文件中的key要有一定的特殊规则 -->
    <context:property-placeholder location="classpath:application.properties" ignore-unresolvable="true"/>            //数据库的连接属性
    <!-- 配置数据源,使用dbcp连接池 -->
    <!-- 配置数据源,使用dbcp连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="30"/>
        <property name="maxIdle" value="5"/>
    </bean>
    <!-- 配置SqlSessionFactory -->                                                                                                                                              //mybatis-spring.jar的整合包功能导入
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:sql-map-config.xml" />
    </bean>



    <!-- 配置Mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包路径,如果需要扫描多个包中间用半角逗号隔开 -->
        <property name="basePackage" value="com.terabits.mapper"/>
        <!-- 这边不能使用ref="sqlSessionFactory"原因是因为上面加载配置文件导致这边引用会报错 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
    
    <!-- 事务控制  对MyBatis操作数据库  spring使用JDBC事务控制类 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
        <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>


        </tx:attributes>
    </tx:advice>
    <!-- 配置aop  -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.terabits.service.impl.*.*(..))"/>
    </aop:config>

    
</beans>

然后是web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">


  <display-name>SpringMVCDemo Web Application</display-name>


  <!-- spring容器监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 加载spring容器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>                                                     //导入applicationContext.xml配置文件
    <param-value>classpath*:applicationContext*.xml</param-value>
  </context-param>


<!--定义SpingMVC的前端控制器-->
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--编码过滤器-->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>


为了实现事务管理以及利用mybatis-spring.jar整合包,主要是要注意表红色的地方,其它的都可以根据具体情况进行删减改动。

在介绍完配置文件之后,接下来是代码部分的需要注意的地方。

利用mybatis-spring.jar整合包,就不需要自己取建立sqlsessionfactory这些了。因此,在DAO层,不需要写接口和其实现类,只需要写类就可以了。

类似于这种形式:

@Repository("userDAO")public class UserDAO {@Autowired    private UserMapper userMapper;public List<RechargesVO> selectRecharge(String beginTime, String endTime, String phone)  throws Exception{return userMapper.selectRecharge(beginTime, endTime, phone);}}


还有一点需要注意的是,为了实现事务管理,建议把所有的事务逻辑都放到service层的service实现类中。然后再在类或者public方法上加上@transactional注解即可

类似于

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)@Service("userService")public class UserServiceImpl implements UserService {@Autowiredprivate UserDAO userDAO;@Overridepublic JSONArray getRecharges(String beginTime, String endTime, String phone){List<RechargeVO> rechargeVOs = new ArrayList<RechargeVO>();double money = 0;try {rechargeVOs = userDAO.selectRecharge(beginTime, endTime, phone);JSONArray jsonArray = JSONArray.fromObject(rechargeVOs);return jsonArray;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}


这样就实现了事务管理。

阅读全文
1 0
原创粉丝点击