Mybatis 测试事务

博客介绍了Spring相关内容并进行案例学习,涉及CustomerService.java类、CustomerServiceImpl实现类,在Spring配置文件中开启扫描后进行单元测试,还提到开启事务@Transactional后,若出现异常数据库不会添加数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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开启后,一旦出现异常,数据库不会添加数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值