| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
admin
9年前发布

MyBatis+Spring 事务管理

在网上查了MyBatis+Spring的结合,真的是太多太多了,可是没有几个代码是完整的..这两项整合花了我两天时间,终于被我整合完成...其实也很简单,原 因:JAR包的问题... 由于Ibatis被改名为MyBatis,所以,网上很多都是有关Ibatis而MyBatis却很少很少... 本文以MyBatis3.0.6 + Spring3.0.6为例结合(一定要这个版本才行):出处:http://kinglixing.blog.51cto.com/3421535/723870

实体类:Emp.java

package com.lixing.scm.entity;    public class Emp {    private String id;    private String name;    private String sex;    private int age;    private String phone;    public String getId() {      return id;    }    public void setId(String id) {      this.id = id;    }    public String getName() {      return name;    }    public void setName(String name) {      this.name = name;    }    public String getSex() {      return sex;    }    public void setSex(String sex) {      this.sex = sex;    }    public int getAge() {      return age;    }    public void setAge(int age) {      this.age = age;    }    public String getPhone() {      return phone;    }    public void setPhone(String phone) {      this.phone = phone;    }  }

定义实体内操作接口:EmpMapper.java

package com.lixing.scm.test.mapper;    import java.util.List;  import java.util.Map;    import com.lixing.scm.entity.Emp;    public interface EmpMapper {    void insertEmp(Emp emp);    List<Emp> getAllEmp();    Emp getById(String id);    void deleteEmp(String id);    void updateEmp(Map<String,Object> map);  }

定义实体类操作接口的映射文件:EmpMapper.xml

<?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.lixing.scm.test.mapper.EmpMapper">     <parameterMap type="com.lixing.scm.entity.Emp" id="parameterMapEmp">      <parameter property="id"/>      <parameter property="name"/>      <parameter property="sex"/>      <parameter property="age"/>      <parameter property="phone"/>    </parameterMap>      <resultMap type="com.lixing.scm.entity.Emp" id="resultMapEmp">      <result property="id" column="id"/>      <result property="name" column="name"/>      <result property="sex" column="sex"/>      <result property="age" column="age"/>      <result property="phone" column="phone"/>    </resultMap>      <insert id="insertEmp" parameterMap="parameterMapEmp">      INSERT INTO emp(id,name,sex,age,phone)      VALUES(?,?,?,?,?)    </insert>    <select id="getAllEmp"    resultMap="resultMapEmp">      SELECT * FROM emp    </select>    <select id="getById" parameterType="String" resultMap="resultMapEmp">      SELECT * FROM emp      WHERE id=#{value}    </select>    <delete id="deleteEmp" parameterType="String">      DELETE FROM emp       WHERE id=#{value}    </delete>    <update id="updateEmp" parameterType="java.util.Map">      UPDATE emp      SET name=#{name},sex=#{sex},age=#{age},phone=#{phone}      WHERE id=#{id}    </update>  </mapper>

Spring3.0.6定义: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:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx"    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/tx           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd           http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">      <!--    -->    <context:annotation-config />    <context:component-scan base-package="com.lixing.scm.test.*" />      <!-- jdbc.propertis Directory -->    <bean      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">      <property name="locations" value="classpath:jdbc.properties" />    </bean>      <bean id="MyDataSource" destroy-method="close"      class="org.apache.commons.dbcp.BasicDataSource">      <property name="driverClassName" value="${jdbc.driverClassName}" />      <property name="url" value="${jdbc.url}" />      <property name="username" value="${jdbc.username}" />      <property name="password" value="${jdbc.password}" />    </bean>      <!-- SqlSessionFactory -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">      <property name="dataSource" ref="MyDataSource" />    </bean>    <!-- ScanMapperFiles -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">      <property name="basePackage" value="com.lixing.scm.test.mapper" />    </bean>      <!-- ================================事务相关控制=================================================    -->    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">                 <property name="dataSource" ref="MyDataSource"></property>      </bean>           <tx:advice id="userTxAdvice" transaction-manager="transactionManager">      <tx:attributes>        <tx:method name="delete*" propagation="REQUIRED" read-only="false"                               rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/>        <tx:method name="insert*" propagation="REQUIRED" read-only="false"                               rollback-for="java.lang.RuntimeException" />        <tx:method name="update*" propagation="REQUIRED" read-only="false"                               rollback-for="java.lang.Exception" />          <tx:method name="find*" propagation="SUPPORTS"/>        <tx:method name="get*" propagation="SUPPORTS"/>        <tx:method name="select*" propagation="SUPPORTS"/>      </tx:attributes>    </tx:advice>      <aop:config>          <aop:pointcut id="pc" expression="execution(public * com.lixing.scm.test.service.*.*(..))" /> <!--把事务控制在Service层-->      <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />    </aop:config>      <!-- 以下为自定义Bean-->    <bean id="empDao" class="com.lixing.scm.test.dao.impl.EmpDaoImpl"      autowire="byName" />      <bean id="empService" class="com.lixing.scm.test.service.impl.EmpServiceImpl"    autowire="byName"/>  </beans>

DAO接口:EmpDAO.java

package com.lixing.scm.test.dao;    import java.util.List;  import java.util.Map;    import com.lixing.scm.entity.Emp;    public interface EmpDao {    void insertEmp(Emp emp);    List<Emp> getAllEmp();    Emp getById(String id);    void deleteEmp(String id);    void updateEmp(Map<String, Object> map);  }

DAO接口实现类:EmpDaoImpl.java

package com.lixing.scm.test.dao.impl;    import java.util.List;  import java.util.Map;    import com.lixing.scm.entity.Emp;  import com.lixing.scm.test.dao.EmpDao;  import com.lixing.scm.test.mapper.EmpMapper;    public class EmpDaoImpl implements EmpDao {    private EmpMapper empMapper;   //在此处注入一个empMapper                          //这个empMapper由 Spring自动生成                       //不需要我们自己手工去定义    @Override    public void insertEmp(Emp emp) {      this.empMapper.insertEmp(emp);      throw new RuntimeException("Error");   //测试抛出RuntimeException                           //异常查看数据库是否存在记录    }      @Override    public void deleteEmp(String id) {      this.empMapper.deleteEmp(id);    }      @Override    public List<Emp> getAllEmp() {      return this.empMapper.getAllEmp();    }      @Override    public Emp getById(String id) {      return this.empMapper.getById(id);    }      @Override    public void updateEmp(Map<String, Object> map) {      this.empMapper.updateEmp(map);    }      public EmpMapper getEmpMapper() {      return empMapper;    }      public void setEmpMapper(EmpMapper empMapper) {      this.empMapper = empMapper;    }  }

Service层接口:EmpService.java

package com.lixing.scm.test.service;    import com.lixing.scm.entity.Emp;    public interface EmpService {    void insertEmp(Emp emp);  }

Service层接口实现类:EmpServiceImpl.java

package com.lixing.scm.test.service.impl;    import com.lixing.scm.entity.Emp;  import com.lixing.scm.test.dao.EmpDao;  import com.lixing.scm.test.service.EmpService;    public class EmpServiceImpl implements EmpService {    private EmpDao empDao;      @Override    public void insertEmp(Emp emp) {      empDao.insertEmp(emp);      }      public EmpDao getEmpDao() {      return empDao;    }      public void setEmpDao(EmpDao empDao) {      this.empDao = empDao;    }  }

测试类:TestEmpService.java

import org.junit.Test;  import org.springframework.context.ApplicationContext;  import org.springframework.context.support.ClassPathXmlApplicationContext;    import com.lixing.scm.entity.Emp;  import com.lixing.scm.test.service.EmpService;    public class TestEmpService {    @Test    public void testTrasaction(){      Emp emp=new Emp();      emp.setId("00000003");      emp.setName("某某某");      emp.setAge(50);      emp.setSex("男");      emp.setPhone("566666");        ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");      EmpService service=ctx.getBean(EmpService.class);      service.insertEmp(emp);    }  }