在 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程序后 查询数据库,发现增加了一条数据。