@Overridepublic int insertAccount(Account account) {int num = 0;num = accountMapper.insertAccount(account);System.out.println("添加用户成功,num="+num);//手动抛出异常System.out.println(1/0);//出现错误的时候我们不希望数据插入进数据库return num;}
如果都出错了已经插入到用户表中的数据撤销掉,这就是事务的意义
添加事务(添加注解式的事务)
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!--直接导入applicationContext_mapper.xml--><import resource="applicationContext_mapper.xml"/><!--SM是基于注解的开发,所以添加包扫描--><context:component-scan base-package="com.chentianyu.service.impl" /><!--事务处理--><!--1.添加事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--因为事务必须关联数据库处理,所以要配置数据源--><property name="dataSource" ref="dataSource" /></bean><!--2.添加事务的注解驱动--><!--annotation-driven以tx后缀为主:http://www.springframework.org/schema/tx/spring-tx.xsdtransaction-manager:属性,挂的是书屋管理器的id--><tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven></beans>
这样还是不行的,要在你想要开启事务的类上添加@Transactional
package com.chentianyu.service.impl;
import com.chentianyu.mapper.AccountMapper;
import com.chentianyu.pojo.Account;
import com.chentianyu.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service//业务逻辑层
@Transactional(propagation = Propagation.REQUIRED/*事务的传播特性,增删改必走这个特性*/)
public class AccountServiceImpl implements AccountService {
//但凡是业务逻辑层的实现类,一定会有数据访问层的对象
@Autowired
AccountMapper accountMapper;
@Override
public int insertAccount(Account account) {
int num = 0;
num = accountMapper.insertAccount(account);
System.out.println("添加用户成功,num="+num);
//手动抛出异常
System.out.println(1/0);//出现错误的时候我们不希望数据插入进数据库
return num;
}
}
