MyBatis与Spring 整合之测试事务

在 MyBatis 与Spring的整合中 配置了事务管理器,并开启了事务注解,但还不能够确定是否配置正确,以及事务能否生效。

如下代码,测试验证:

1.在CustomerMapper 接口中增加方法

  public void addCustomer(Customer customer);

并在映射文件中编写执行插入操作的SQL配置

   <insert id="addCustomer" parameterType = "Customer">
     insert into t_customer(username,jobs,phone) values(#{username},#{jobs},#{phone})
  </insert>


2.在src目录下创建com.kangxg.service 包并创建CustomerService接口,并增加方法

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


3.在src目录下创建com.kangxg.service.impl 包并创建CustomerServiceImpl类

package com.kangxg.service.impl;

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

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

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
     @Autowired
     private CustomerMapper  customerMapper;
     public void addCustomer(Customer customer)
     {
         this.customerMapper.addCustomer(customer);
         //设置异常代码
         int i = 1/0;
     }
}


4.在Spring的配置文件中,编写开始注解扫描的配置代码

<context:component-scan base-package ="com.kangxg.service" />


5.在测试文件中增加测试方法

@Test
    public void addCustomerTest()throws Exception
    {
        String xmlPath = "applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        CustomerService customerService = applicationContext.getBean(CustomerService.class);
        // 创建 Customer 类型对戏对象,并向对象添加数据
        Customer customer = new Customer();
        customer.setIUsername("mff");
        customer.setJobs("test");
        customer.setPhone("98765432101");
        customerService.addCustomer(customer);

    }

6 debug jUnit

这时候,进入数据库中查询,发现并没有增加数据说明事务已经生效,如果把 CustomerServiceImpl 类中@Transactional 注释掉,再次 debug程序后 查询数据库,发现增加了一条数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值