SpringMVC,Mybatis结合事务Transaction

SpringMVC,Mybatis结合事务Transaction
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203
前面讲过,Spring事务就是针对某一个方法,在头和尾环绕上一对儿事务的开始和结束语句段,方法里针对数据库的操作就成为了一个事务。具体怎么样访问数据库,是JDBC,还是Spring JDBC还是Mybatis,Spring的事务并不关心。所以mybatis这里的事务的配置和实验和前面的Spring JDBC是一样的。

例 1.5

package com;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class HelloWorldController {
    @Resource
    private ILoginService loginServic;
    @RequestMapping("/helloa")
    public void helloWorld(HttpServletResponse res) throws IOException {
        loginServic.login();
        res.sendRedirect("index.jsp");
    }
}



package com;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.mapper.RegisterMapper;
@Service
public class LoginServiceImpl implements ILoginService {
    @Resource
    private RegisterMapper registerMapper;

    public void login() {
        updateRegister();
        System.out.println("successfully update 1");
        insertRegisterWrong();//duplicate key
        System.out.println("successfully insert 2");
    } 
    public void updateRegister() {
        Register registerU = new Register();
        registerU.setId(52);
        registerU.setName("bbb2");
        registerU.setAge(80);
        System.out.println("registerMapper.updateByPrimaryKey 的返回值是 "+registerMapper.updateByPrimaryKey(registerU));
    }
    public void insertRegisterWrong() {
        Register register = new Register();
        register.setAge(80);
        register.setId(50);
        register.setName("aaa");
        registerMapper.insert(register);    }
}




<?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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:p="http://www.springframework.org/schema/p"
    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.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        ">
 
    <context:component-scan
        base-package="com" />
 
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
         <property name="driverClassName"
                      value="com.mysql.jdbc.Driver"></property>
         <property name="url"
                      value="jdbc:mysql://localhost:3306/test"></property>
         <property name="username"
                      value="root"></property>
         <property name="password"
                      value="1234"></property>
    </bean>
<!-- 通过扫描的模式,扫描目录在com.mapper目录下,把所有mapper都注入到Spring当中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.mapper" />
    </bean>
<!-- 没有以下的话,所有的mapper都不能创建,服务器启动过程报错-->  
    <bean id="sqlSessionFactoryqqqq" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
        <!-- 配置切面 这种写法也正确"execution(* service.*.*(..))"-->
    <aop:config>
        <aop:pointcut id="myPointcut" expression="execution(* com.LoginServiceImpl.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>     
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="login*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <bean id="transactionManager"
 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>




package com;
public interface ILoginService {
/*在Controller当中有iLoginService.login,所以在接口中必须有login方法*/  
    public void login();
}


package com.mapper;
import com.Register;
public interface RegisterMapper {
    Register selectByPrimaryKey(Integer id);
    int insert(Register record);
    int updateByPrimaryKey(Register record);
}



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.RegisterMapper">
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultType="com.Register">
    select Id, Name, Age from register
    where Id = #{id,jdbcType=INTEGER}
  </select>
  <insert id="insert" parameterType="com.Register">
    insert into register (Id, Name, Age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
  <update id="updateByPrimaryKey" parameterType="com.Register">
    update register
    set Name = #{name,jdbcType=VARCHAR},
      Age = #{age,jdbcType=INTEGER}
    where Id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

实验结果:
当数据库开始有id52的数据时,可以更新也可以添加。但同样的程序第二次执行时,就报错了,因为id50的数据已经有了,不能再次添加了。