天天看点

使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层

1.jar包

使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层

2.层次结构

使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层

3.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.yw.*" />


	<!-- 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="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${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.yw.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.yw.service.*.*(..))" /> <!--把事务控制在Service层 -->
		<aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
	</aop:config>


	<!-- 以下为自定义Bean -->
	<bean id="empDao" class="com.yw.dao.impl.EmpDaoImpl" autowire="byName" />
	<bean id="empService" class="com.yw.service.impl.EmpServiceImpl"
		autowire="byName" />
</beans>
           

4.jdbc.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ywdb
username=root
password=root
           

5.

package com.yw.pojo;

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;
	}

	@Override
	public String toString()
	{
		return "Emp [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", phone=" + phone + "]";
	}
	
	
}
           

5.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.yw.mapper.EmpMapper">
  <parameterMap type="com.yw.pojo.Emp" id="parameterMapEmp">
    <parameter property="id"/>
    <parameter property="name"/>
    <parameter property="sex"/>
    <parameter property="age"/>
    <parameter property="phone"/>
  </parameterMap>
  
  <resultMap type="com.yw.pojo.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(name,sex,age,phone)
    VALUES(#{name},#{sex},#{age},#{phone})
  </insert>
  <select id="getAllEmp"    resultMap="resultMapEmp">
    SELECT * FROM emp
  </select>
  <select id="getById" parameterType="String" resultMap="resultMapEmp">
    SELECT * FROM emp
    WHERE id=#{id}
  </select>
  <delete id="deleteEmp">
    DELETE FROM emp
    WHERE id=#{id}
  </delete>
  <update id="updateEmp" >
    UPDATE emp
    SET name=#{name},sex=#{sex},age=#{age},phone=#{phone}
    WHERE id=#{id}
  </update>
</mapper>
           
package com.yw.mapper;

import java.util.List;
import java.util.Map;

import com.yw.pojo.Emp;

public interface EmpMapper
{
	void insertEmp(Emp emp);

	List<Emp> getAllEmp();

	Emp getById(int id);

	void deleteEmp(int id);

	void updateEmp(Emp emp);
}
           
package com.yw.dao;

import java.util.List;
import java.util.Map;

import com.yw.pojo.Emp;

public interface EmpDao
{
	void insertEmp(Emp emp);

	List<Emp> getAllEmp();

	Emp getById(int id);

	void deleteEmp(int id);

	void updateEmp(Emp emp);
}
           
package com.yw.dao.impl;

import java.util.List;
import java.util.Map;

import com.yw.dao.EmpDao;
import com.yw.mapper.EmpMapper;
import com.yw.pojo.Emp;

public class EmpDaoImpl implements EmpDao
{
	private EmpMapper empMapper; // 在此处注入一个empMapper

	public EmpDaoImpl()
	{
		System.out.println("==EmpDaoImpl()====");
		System.out.println("empMapper=" + empMapper);
	}

	// 这个empMapper由 Spring自动生成 //不需要我们自己手工去定义
	@Override
	public void insertEmp(Emp emp)
	{

		this.empMapper.insertEmp(emp);
//		throw new RuntimeException("yw测试抛出RuntimeException"); // 测试抛出RuntimeException //异常查看数据库是否存在记录

	}

	@Override
	public void deleteEmp(int id)
	{
		this.empMapper.deleteEmp(id);
	}

	@Override
	public List<Emp> getAllEmp()
	{
		return this.empMapper.getAllEmp();
	}

	@Override
	public Emp getById(int id)
	{
		return this.empMapper.getById(id);
	}

	@Override
	public void updateEmp(Emp emp)
	{
		this.empMapper.updateEmp(emp);
	}

	public EmpMapper getEmpMapper()
	{
		return empMapper;
	}

	public void setEmpMapper(EmpMapper empMapper)
	{
		this.empMapper = empMapper;
	}
}
           
package com.yw.service;

import java.util.List;

import com.yw.pojo.Emp;

public interface EmpService
{
	void insertEmp(Emp emp);

	List<Emp> getAllEmp();

	Emp getById(int id);

	void deleteEmp(int id);

	void updateEmp(Emp emp);
}
           
package com.yw.service.impl;

import java.util.List;

import com.yw.dao.EmpDao;
import com.yw.pojo.Emp;
import com.yw.service.EmpService;

public class EmpServiceImpl implements EmpService
{
	private EmpDao empDao;

	public EmpServiceImpl()
	{
		System.out.println("==EmpServiceImpl()==");

	}

	@Override
	public void insertEmp(Emp emp)
	{

		empDao.insertEmp(emp);
		List emps=empDao.getAllEmp();
		System.out.println("emps="+emps);

	}

	public EmpDao getEmpDao()
	{
		return empDao;
	}

	public void setEmpDao(EmpDao empDao)
	{
		this.empDao = empDao;
	}

	@Override
	public List<Emp> getAllEmp()
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Emp getById(int id)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void deleteEmp(int id)
	{
		empDao.deleteEmp(id);
		List emps=empDao.getAllEmp();
		System.out.println("emps="+emps);
		
	}

	@Override
	public void updateEmp(Emp emp)
	{
		// TODO Auto-generated method stub
		
	}
}
           
package com.yw.test;

import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.yw.pojo.Emp;
import com.yw.service.EmpService;

public class Test01
{
    public static void main(String[] args)
    {
        Emp emp = new Emp();

        emp.setName("lisi2");
        emp.setAge(54);
        emp.setSex("male");
        emp.setPhone("566666");

        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        // System.out.println("ctx="+ctx);
        // EmpDaoImpl obj=(EmpDaoImpl)ctx.getBean("empDao");
        // System.out.println("EmpMapper="+obj.getEmpMapper());
        //
        Object sessionFactory = ctx.getBean("sqlSessionFactory");
        System.out.println("sessionFactory=" + sessionFactory);

        System.out.println("=================测试调用service========================");

        DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) ctx
                .getBean("transactionManager");
        System.out.println("transactionManager=" + transactionManager);
        // Connection conn = null;
        try
        {
            // conn = transactionManager.getDataSource().getConnection();
            // System.out.println("conn=" + conn);
            EmpService service = ctx.getBean(EmpService.class);
            service.insertEmp(emp);
        }
        catch (RuntimeException e)
        {
            System.out.println(e.getMessage());
        }
//        catch (SQLException e1)
//        {
//            // TODO Auto-generated catch block
//            e1.printStackTrace();
//        }

        // System.out.println("=================测试再次调用service========================");
        //
        // DataSourceTransactionManager transactionManager2 = (DataSourceTransactionManager) ctx
        // .getBean("transactionManager");
        // System.out.println("transactionManager2=" + transactionManager2);
        // Connection conn2 = null;
        // try
        // {
        // conn2 = transactionManager2.getDataSource().getConnection();
        // System.out.println("conn==conn2" + (conn == conn2));
        // System.out.println("conn2=" + conn2);
        // EmpService service = ctx.getBean(EmpService.class);
        // service.deleteEmp(7);
        // } catch (RuntimeException e)
        // {
        // System.out.println(e.getMessage());
        // } catch (SQLException e1)
        // {
        // // TODO Auto-generated catch block
        // e1.printStackTrace();
        // }

    }

}
           

6.测试结果

使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层
使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层
使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层
使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层
使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层
使用Spring(13)Spring与MyBatis整合(二)DataSourceTransactionManage把事务控制在Service层