Spring+MyBatis整合

一笑奈何 提交于 2020-03-01 09:59:05

一、准备工作

  1.1准备jar包

  

  

  

  建表语句:

CREATE TABLE `t_customer` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `jobs` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `phone` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

 

 

  1.2编写配置文件:

    1.2.1db.properties   

#dataSource
#Thu Mar 07 16:27:40 CST 2019
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sm
jdbc.username=root
jdbc.password=123456
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

 

    1.2.2 beans.xml    

<?xml  version="1.0"  encoding="UTF-8"?> 
<beans  xmlns="http://www.springframework.org/schema/beans" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"         
        xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/context 
             http://www.springframework.org/schema/context/spring-context-4.3.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop-4.3.xsd" > 
    <!-- 读取 db.properties-->
    <context:property-placeholder location = "classpath:db.properties"/>
    <!-- 配置数据源 -->
    <bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource">
        <!-- 数据库驱动 -->
        <property name = "driverClassName" value = "${jdbc.driver}" />
        <!-- 数据库url -->
        <property name = "url" value = "${jdbc.url}" />
        <!-- 数据库用户名 -->
        <property name = "username" value = "${jdbc.username}" />
        <!-- 数据库密码 -->
        <property name = "password" value = "${jdbc.password}" />
        <!-- 数据库最大连接数 -->
        <property name="maxTotal" value = "${jdbc.maxTotal}"/>
        <!-- 数据库最大空闲数 -->
        <property name="maxIdle" value = "${jdbc.maxIdle}"/>
        <!-- 初始化连接数 -->
        <property name="initialSize" value = "${jdbc.initialSize}"/>
    </bean>
    <!-- 配置事务管理,并指定数据源 -->
    <bean id = "transactionManager" 
            class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name = "dataSource" ref = "dataSource" />
    </bean>
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager = "transactionManager" />
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.sm.service"/>
    <!-- 配置MyBatis工厂 -->
    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref = "dataSource"/>
        <!-- 指定核心配置文件 -->
        <property name="configLocation" value = "classpath:mybatis-config.xml"/>
    </bean>
</beans>

 

    1.2.3 mybatis-config.xml  

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 采用扫描包定义别名 -->
    <typeAliases>
        <package name="com.sm.po"/>
    </typeAliases>
    
    <!-- 配置映射文件 -->
    <mappers>

    </mappers>
</configuration>

 

  

 二、基于Dao方式整合

  2.1在src目录下创建com.sm.po包,并在包中创建Customer类

  Customer.java

package com.sm.po;

public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;
    public Customer() {
        // TODO Auto-generated constructor stub
    }
    public Customer(Integer id, String username, String jobs, String phone) {
        super();
        this.id = id;
        this.username = username;
        this.jobs = jobs;
        this.phone = phone;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getJobs() {
        return jobs;
    }

    public void setJobs(String jobs) {
        this.jobs = jobs;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";
    }
}

 

    2.2在com.sm.po包中创建CustomerMapper.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.sm.po.CustomerMapper" >
        <!-- 根据ID查询客户信息 -->
        <select id = "findCustomerById" parameterType = "Integer" resultType = "customer">
            select * from t_customer where id = #{id}
        </select>
    </mapper>

 

    2.3在mybatis-config.xml中添加映射文件(CustomerMapper.xml)

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 采用扫描包定义别名 -->
    <typeAliases>
        <package name="com.sm.po"/>
    </typeAliases>
    
    <!-- 配置映射文件 -->
    <mappers>
        <!-- 基于Dao -->
        <mapper resource = "com/sm/po/CustomerMapper.xml"/>
    </mappers>
</configuration>

 

    2.4创建一个com.sm.dao包,并在其中创建CustoemrDao接口 

package com.sm.dao;

import com.sm.po.Customer;

public interface CustomerDao {
    public Customer findCustomerById(Integer id);
}

 

    2.5创建一个com.sm.dao.impl包,并在其中创建CustomerDao接口的实现类CustomerDaoImpl.

package com.sm.dao.impl;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.sm.dao.CustomerDao;
import com.sm.po.Customer;

public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao{

    @Override
    public Customer findCustomerById(Integer id) {
        return this.getSqlSession().selectOne("com.sm.po.CustomerMapper.findCustomerById",id);
    }
}

继承了SqlSessionDaoSupport,通过getSqlSession()获取sqlSession,并执行指定SQL语句。

获取SqlSession首先需要设置SqlSessionFactory,SqlSessionFactory通过spring注入。

    SqlSessionDaoSupport :部分源码

      

       Spring就是通过set方法将SqlSessionFactory注入,然后获取sqlSession。  

 

 

    2.6 在beans.xml中将SqlSessionFactory注入   

<?xml  version="1.0"  encoding="UTF-8"?> 
<beans  xmlns="http://www.springframework.org/schema/beans" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"         
        xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/context 
             http://www.springframework.org/schema/context/spring-context-4.3.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop-4.3.xsd" > 
    <!-- 读取 db.properties-->
    <context:property-placeholder location = "classpath:db.properties"/>
    <!-- 配置数据源 -->
    <bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource">
        <!-- 数据库驱动 -->
        <property name = "driverClassName" value = "${jdbc.driver}" />
        <!-- 数据库url -->
        <property name = "url" value = "${jdbc.url}" />
        <!-- 数据库用户名 -->
        <property name = "username" value = "${jdbc.username}" />
        <!-- 数据库密码 -->
        <property name = "password" value = "${jdbc.password}" />
        <!-- 数据库最大连接数 -->
        <property name="maxTotal" value = "${jdbc.maxTotal}"/>
        <!-- 数据库最大空闲数 -->
        <property name="maxIdle" value = "${jdbc.maxIdle}"/>
        <!-- 初始化连接数 -->
        <property name="initialSize" value = "${jdbc.initialSize}"/>
    </bean>
    <!-- 配置事务管理,并指定数据源 -->
    <bean id = "transactionManager" 
            class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name = "dataSource" ref = "dataSource" />
    </bean>
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager = "transactionManager" />
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.sm.service"/>
    <!-- 配置MyBatis工厂 -->
    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref = "dataSource"/>
        <!-- 指定核心配置文件 -->
        <property name="configLocation" value = "classpath:mybatis-config.xml"/>
    </bean>
    <!-- 实例化Bean  dao,并将sqlSeesionFactory注入-->
    <bean id = "customerDao"  class = "com.sm.dao.impl.CustomerDaoImpl">
        <property name="sqlSessionFactory" ref = "sqlSessionFactory"></property>
    </bean>
</beans>

 

     2.7测试 

package com.sm.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sm.dao.CustomerDao;
import com.sm.dao.impl.CustomerDaoImpl;
import com.sm.po.Customer;

public class DaoTest {

    public static void main(String[] args) {
        ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");
        CustomerDao cus = (CustomerDaoImpl)act.getBean("customerDao");
        Customer custoemr =  cus.findCustomerById(1);
        System.out.println(custoemr);
    }
}

 

 

三、基于Mapper接口方式整合

  采用基于Dao方式整合可以实现所需功能,但是也有一定的问题,例如执行语句的路径容易写错。    

    那么有什么方式可以将xxxxMapper.xml中语句的ID与Dao中的方法直接关联起来,这样调用方法时直接调用就可以了,

  避免了自己编写语句路径出错。

  基于Mapper接口方式整合就可以达到这种目的。

  

  3.1在src目录下创建com.sm.mapper包,并在其中创建CustomerMapper.java和其映射文件CustomerMapper.xml。

 

CustomerMapper.java  

package com.sm.mapper;

import com.sm.po.Customer;

public interface CustomerMapper {
    public Customer findCustomerById(Integer id);
    public void addCustomer(Customer customer);
}

 

CustomerMapper.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.sm.mapper.CustomerMapper" >
        <!-- 根据ID查询客户信息 -->
        <select id = "findCustomerById" parameterType = "Integer" resultType = "customer">
            select * from t_customer where id = #{id}
        </select>
    </mapper>

    

    3.2在mybatis-config.xml中配置<mapper resource = "com/sm/mapper/CustomerMapper.xml"/> 

  

    3.3在beans.xml中将映射文件和接口关联起来

  

<?xml  version="1.0"  encoding="UTF-8"?> 
<beans  xmlns="http://www.springframework.org/schema/beans" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"         
        xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/context 
             http://www.springframework.org/schema/context/spring-context-4.3.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop-4.3.xsd" > 
    <!-- 读取 db.properties-->
    <context:property-placeholder location = "classpath:db.properties"/>
    <!-- 配置数据源 -->
    <bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource">
        <!-- 数据库驱动 -->
        <property name = "driverClassName" value = "${jdbc.driver}" />
        <!-- 数据库url -->
        <property name = "url" value = "${jdbc.url}" />
        <!-- 数据库用户名 -->
        <property name = "username" value = "${jdbc.username}" />
        <!-- 数据库密码 -->
        <property name = "password" value = "${jdbc.password}" />
        <!-- 数据库最大连接数 -->
        <property name="maxTotal" value = "${jdbc.maxTotal}"/>
        <!-- 数据库最大空闲数 -->
        <property name="maxIdle" value = "${jdbc.maxIdle}"/>
        <!-- 初始化连接数 -->
        <property name="initialSize" value = "${jdbc.initialSize}"/>
    </bean>
    <!-- 配置事务管理,并指定数据源 -->
    <bean id = "transactionManager" 
            class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name = "dataSource" ref = "dataSource" />
    </bean>
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager = "transactionManager" />
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.sm.service"/>
    <!-- 配置MyBatis工厂 -->
    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref = "dataSource"/>
        <!-- 指定核心配置文件 -->
        <property name="configLocation" value = "classpath:mybatis-config.xml"/>
    </bean>
    
    <!-- 基于mapper  -->
    <bean id = "customerMapper" class = "org.mybatis.spring.mapper.MapperFactoryBean">
        <property name = "mapperInterface" value = "com.sm.mapper.CustomerMapper"/>  <!--指定接口 -->
        <property name = "sqlSessionFactory" ref = "sqlSessionFactory" /> <!-- 指定sqlSessionFactory -->
    </bean>
  
</beans>

 

    测试:

package com.sm.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sm.mapper.CustomerMapper;
import com.sm.po.Customer;

public class MapperTest {
    public static void main(String[] args) {
        ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");
        CustomerMapper customerMapper = act.getBean("customerMapper",CustomerMapper.class);
        Customer customer =  customerMapper.findCustomerById(1);
        System.out.print(customer);
    }
} 

 

 

注:基于Mapper接口整合还需遵循以下规范:

  Mapper接口的名称和对应的Mapper.xml文件的名称必须保持一致。

  Mapper.xml文件中的namespace与Mapper接口的类路径要一致,即这两个文件是放在一个包中的。

  Mapper接口中的方法和Mapper.xml中定义的sql语句的id要相同。

  Mapper接口方法中的参数类型要与Mapper.xml中对应语句的类型(parameterType)相同。

  Mapper接口方法的返回值与Mapper.xml中对应语句的返回值类型(resultType)要相同。

  

  如果以上规范都遵循了,MyBatis就会自动生成Mapper接口实现类的代理对象,从而简化开发。

  而且遵循了以上规范,可以不用再mybatis-config.xml中执行映射文件(<mapper resource = "xxx"/>)

 

三、基于MapperScannerConfigurer的整合

  采用Mapper接口方式整合比基于Dao方式整合方便些,但是依然需要在配置文件(beans.xml)中编写大量配置。

  那有没有更方便的方式呢,只需要指定接口和映射文件即可。

  基于MapperSacnnerConfigurer就可以实现这一点。

  我们将 基于Mapper接口实现整合中beans.xml中的关联部分删除。

 

beans.xml 

<?xml  version="1.0"  encoding="UTF-8"?> 
<beans  xmlns="http://www.springframework.org/schema/beans" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"         
        xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/context 
             http://www.springframework.org/schema/context/spring-context-4.3.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop-4.3.xsd" > 
    <!-- 读取 db.properties-->
    <context:property-placeholder location = "classpath:db.properties"/>
    <!-- 配置数据源 -->
    <bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource">
        <!-- 数据库驱动 -->
        <property name = "driverClassName" value = "${jdbc.driver}" />
        <!-- 数据库url -->
        <property name = "url" value = "${jdbc.url}" />
        <!-- 数据库用户名 -->
        <property name = "username" value = "${jdbc.username}" />
        <!-- 数据库密码 -->
        <property name = "password" value = "${jdbc.password}" />
        <!-- 数据库最大连接数 -->
        <property name="maxTotal" value = "${jdbc.maxTotal}"/>
        <!-- 数据库最大空闲数 -->
        <property name="maxIdle" value = "${jdbc.maxIdle}"/>
        <!-- 初始化连接数 -->
        <property name="initialSize" value = "${jdbc.initialSize}"/>
    </bean>
    <!-- 配置事务管理,并指定数据源 -->
    <bean id = "transactionManager" 
            class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name = "dataSource" ref = "dataSource" />
    </bean>
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager = "transactionManager" />
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.sm.service"/>
    <!-- 配置MyBatis工厂 -->
    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref = "dataSource"/>
        <!-- 指定核心配置文件 -->
        <property name="configLocation" value = "classpath:mybatis-config.xml"/>
    </bean>
    <!-- 基于mapper   注释关联部分 -->
    <!-- <bean id = "customerMapper" class = "org.mybatis.spring.mapper.MapperFactoryBean">
        <property name = "mapperInterface" value = "com.sm.mapper.CustomerMapper"/>
        <property name = "sqlSessionFactory" ref = "sqlSessionFactory" />
    </bean>  -->
    <!-- 基于MapperScannerConfigurer  指定basePackage,会自动扫描指定包,将包中映射文件和接口类关联 -->
    <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name = "basePackage" value = "com.sm.mapper"/>
    </bean>
</beans>

  采用自动扫描就可以省去繁琐的配置,使接口类和映射文件自动关联。

 

 

 

四、测试事务

   4.1 将com.sm.mapper包中CustomerMapper.java和CustomerMapper.xml中加入添加方法。

  

CustomerMapper.java  

package com.sm.mapper;

import com.sm.po.Customer;

public interface CustomerMapper {
    public Customer findCustomerById(Integer id);
    public void addCustomer(Customer customer);
}

 

CustomerMapper.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.sm.mapper.CustomerMapper" >
        <!-- 根据ID查询客户信息 -->
        <select id = "findCustomerById" parameterType = "Integer" resultType = "customer">
            select * from t_customer where id = #{id}
        </select>
        
        <!-- 添加用户 -->
        <insert id="addCustomer" parameterType = "customer">
            insert into t_customer(username,jobs,phone)
            values(#{username}, #{jobs}, #{phone})
        </insert>
    </mapper>

 

  4.2创建com.sm.service包,并创建CustomerService接口  

package com.sm.service;

import com.sm.po.Customer;

public interface CustomerService {
    public void addCustomer(Customer customer);
}

  

  4.3创建com.sm.serviceImpl包,并创建CustomerServiceImpl实现类  

package com.sm.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sm.mapper.CustomerMapper;
import com.sm.po.Customer;
import com.sm.service.CustomerService;

@Service
public class CustomerServiceImpl implements CustomerService{
    @Autowired  //按类型装配,使用注解自动注入
    private CustomerMapper customerMapper;
    //@Transactional //事务
    @Override
    public void addCustomer(Customer customer) {
        customerMapper.addCustomer(customer);
        int i = 1/0;
    }
}

  首先注释掉事务,如果没有事务addCustomer方法及时int i = 1/0报错,插入语句也会成功将数据插入。

  如果有事务,int i = 1/0报错,插入也会失败。此处注释事务,比较注释前后区别。

 

  4.4在beans.xml中采用自动扫描方式注册bean

 beans.xml 

<?xml  version="1.0"  encoding="UTF-8"?> 
<beans  xmlns="http://www.springframework.org/schema/beans" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"         
        xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/context 
             http://www.springframework.org/schema/context/spring-context-4.3.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop-4.3.xsd" > 
    <!-- 读取 db.properties-->
    <context:property-placeholder location = "classpath:db.properties"/>
    <!-- 配置数据源 -->
    <bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource">
        <!-- 数据库驱动 -->
        <property name = "driverClassName" value = "${jdbc.driver}" />
        <!-- 数据库url -->
        <property name = "url" value = "${jdbc.url}" />
        <!-- 数据库用户名 -->
        <property name = "username" value = "${jdbc.username}" />
        <!-- 数据库密码 -->
        <property name = "password" value = "${jdbc.password}" />
        <!-- 数据库最大连接数 -->
        <property name="maxTotal" value = "${jdbc.maxTotal}"/>
        <!-- 数据库最大空闲数 -->
        <property name="maxIdle" value = "${jdbc.maxIdle}"/>
        <!-- 初始化连接数 -->
        <property name="initialSize" value = "${jdbc.initialSize}"/>
    </bean>
    <!-- 配置事务管理,并指定数据源 -->
    <bean id = "transactionManager" 
            class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name = "dataSource" ref = "dataSource" />
    </bean>
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager = "transactionManager" />
    <!-- 扫描注解,扫描指定包,为其注册 -->
    <context:component-scan base-package="com.sm.service"/>
    <!-- 配置MyBatis工厂 -->
    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref = "dataSource"/>
        <!-- 指定核心配置文件 -->
        <property name="configLocation" value = "classpath:mybatis-config.xml"/>
    </bean>
   
    <!-- 基于MapperScannerConfigurer -->
    <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name = "basePackage" value = "com.sm.mapper"/>
    </bean>
</beans>

 

    测试:

package com.sm.test;

import org.springframework.context.ApplicationContext;

import com.my.util.MyBatisUtil;
import com.sm.mapper.CustomerMapper;
import com.sm.po.Customer;
import com.sm.service.CustomerService;
import com.sm.service.impl.CustomerServiceImpl;

public class TransactionTest {
    public static void main(String[] args) {
        ApplicationContext act = MyBatisUtil.getApplicationContext("beans.xml");
        CustomerService cs = act.getBean(CustomerService.class);
        cs.addCustomer(new Customer(10, "hhh", "stu", "177xxxx1234"));
    }
}

没有注释事务注解,方法执行失败,但数据仍然会被插入表中。

我们将事务的注释去掉,再运行会发现方法执行失败,但数据不会被插入表中。 

  

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!