介绍
该注解表示数据库事务管理,是spring框架的注解,springboot也可以使用
使用
- 可以修饰 类,该类的 所有方法 都有事务管理
- 可以修饰 方法,表示 该方法 有事务管理
使用该注解管理事务,与传统配置文件方式,更加灵活
源代码
如下:
package org.springframework.transaction.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {
@AliasFor("transactionManager")
String value() default "";
@AliasFor("value")
String transactionManager() default "";
Propagation propagation() default Propagation.REQUIRED;
Isolation isolation() default Isolation.DEFAULT;
int timeout() default -1;
boolean readOnly() default false;
Class<? extends Throwable>[] rollbackFor() default {};
String[] rollbackForClassName() default {};
Class<? extends Throwable>[] noRollbackFor() default {};
String[] noRollbackForClassName() default {};
}
value 和 transactionManager 属性
它们两个是一样的意思。当配置了多个事务管理器时,可以使用该属性指定选择哪个事务管理器。
propagation 属性
事务的传播行为
https://www.malaoshi.top/show_1EF5sipuDU3C.html
isolation 属性
事务的隔离级别,默认值为 Isolation.DEFAULT,即:数据库默认隔离级别
https://www.malaoshi.top/show_1EF5siLLQK3h.html
timeout 属性
事务的超时时间,默认值为-1。如果超过该时间限制但事务还没有完成,则自动回滚事务。
https://www.malaoshi.top/show_1EF5si7DRo2R.html
readOnly 属性
指定事务是否为只读事务,默认值为 false
https://www.malaoshi.top/show_1EF5siIJtRte.html
rollbackFor 属性
用于指定能够触发事务回滚的异常类型,可以指定多个异常类型。
https://www.malaoshi.top/show_1EF5sjIAqWPb.html
noRollbackFor 属性
抛出指定的异常类型,不回滚事务,也可以指定多个异常类型。
https://www.malaoshi.top/show_1EF5sjIAqWPb.html
使用
一般service方法中,有多次增删改操作,需要事务管理,常用注解配置:
修饰类
表示该类的所有方法都有事务管理
@Transactional(rollbackFor = Exception.class)
@Service("GoodsSrv")
public class GoodsSrv{
}
修饰方法
表示该方法有事务管理
@Service
public class UserSrvImpl{
@Transactional(rollbackFor = Exception.class)
public int save(){
}
}