@Transactional
public
class
UserServiceImpl
implements
UserService{
private
JdbcTemplate jdbcTemplate;
@Override
@Transactional
(rollbackFor=Exception.
class
)
public
void
delete(
int
userid)
throws
Exception{
jdbcTemplate.update(
"delete user where id=?"
,
new
Object[]{userid},
new
int
[]{java.sql.Types.INTEGER});
throw
new
Exception(
"hello"
);
}
}
对于在类前用
@Transactional
声明的事务,则类中所有的方法都被声明了事务,
而
@Transactional
声明后默认情况下,所有方法如果抛出的是unchecked异常,
也即RuntimeException,则事务回滚,如果抛出的是checked异常,即Exception,则事务不回滚
因此如果想让方法在抛出checked异常时也回滚,
则可以在方法前加上这样的注释
@Transactional
(rollbackFor=Exception.
class
),这样则表示该方法抛出checked异常时也回滚,
当然也可以让方法抛出unchecked异常不进行回滚,
只需要在方法前面加上注释
@Transactional
(noRollbackFor=RuntimeException.
class
)即可