1.简介
2.案例学习
CustomerService .java类
package com.lin.service;
import com.lin.po.Customer;
public interface CustomerService {
public void addCustomer(Customer customer);
}
CustomerServiceImpl 实现类
package com.lin.service.Impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lin.mapper.CustomerMapper;
import com.lin.po.Customer;
import com.lin.service.CustomerService;
@Service
//管理事务
@Transactional
public class CustomerServiceImpl implements CustomerService{
//注解注入CustomerM
@Autowired
private CustomerMapper customerMapper;
//添加客户
@Override
public void addCustomer(Customer customer) {
// TODO Auto-generated method stub
this.customerMapper.addCustomer(customer);
int i=1/0;//模拟添加操作后,系统突然出现的异常问题
}
}
在Spring配置文件中加入开启扫描
<!-- 注解配置,开启扫描 -->
<context:component-scan base-package="com.lin.service"></context:component-scan>
单元测试
//测试事务
@Test
public void addCustomerTest() {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService customerService= applicationContext.getBean(CustomerService.class);
Customer customer=new Customer();
customer.setUsername("zhangsan");
customer.setJobs("manager");
customer.setPhone("12358792486");
customerService.addCustomer(customer);
}
当事务@Transactional开启后,一旦出现异常,数据库不会添加数据