有人能通过真实的例子解释@Transactional注释中的隔离和传播参数是用于什么吗?

基本上,我应该在什么时候以及为什么选择更改它们的默认值。


当前回答

事务表示数据库的一个工作单元。具有自己的txns(或没有txn)的多个服务中的事务行为称为事务传播。事务隔离定义了当两个事务并发作用于同一个数据库实体时的数据库状态。

TransactionDefinition接口,该接口定义了与spring兼容的事务属性。@Transactional注释描述方法或类上的事务属性。

@Autowired
private TestDAO testDAO;

@Transactional(propagation=TransactionDefinition.PROPAGATION_REQUIRED,isolation=TransactionDefinition.ISOLATION_READ_UNCOMMITTED)
public void someTransactionalMethod(User user) {

  // Interact with testDAO

}

传播(复制):用于事务间的关系。(类似于Java线程间通信)

+-------+---------------------------+------------------------------------------------------------------------------------------------------+
| value |        Propagation        |                                             Description                                              |
+-------+---------------------------+------------------------------------------------------------------------------------------------------+
|    -1 | TIMEOUT_DEFAULT           | Use the default timeout of the underlying transaction system, or none if timeouts are not supported. |
|     0 | PROPAGATION_REQUIRED      | Support a current transaction; create a new one if none exists.                                      |
|     1 | PROPAGATION_SUPPORTS      | Support a current transaction; execute non-transactionally if none exists.                           |
|     2 | PROPAGATION_MANDATORY     | Support a current transaction; throw an exception if no current transaction exists.                  |
|     3 | PROPAGATION_REQUIRES_NEW  | Create a new transaction, suspending the current transaction if one exists.                          |
|     4 | PROPAGATION_NOT_SUPPORTED | Do not support a current transaction; rather always execute non-transactionally.                     |
|     5 | PROPAGATION_NEVER         | Do not support a current transaction; throw an exception if a current transaction exists.            |
|     6 | PROPAGATION_NESTED        | Execute within a nested transaction if a current transaction exists.                                 |
+-------+---------------------------+------------------------------------------------------------------------------------------------------+

隔离:隔离是数据库事务的ACID(原子性、一致性、隔离性、持久性)属性之一。隔离决定了事务完整性如何对其他用户和系统可见。它用于资源锁定,即并发控制,确保在给定的点上只有一个事务可以访问资源。

锁定感知:隔离级别决定持有锁的持续时间。

+---------------------------+-------------------+-------------+-------------+------------------------+
| Isolation Level Mode      |  Read             |   Insert    |   Update    |       Lock Scope       |
+---------------------------+-------------------+-------------+-------------+------------------------+
| READ_UNCOMMITTED          |  uncommitted data | Allowed     | Allowed     | No Lock                |
| READ_COMMITTED (Default)  |   committed data  | Allowed     | Allowed     | Lock on Committed data |
| REPEATABLE_READ           |   committed data  | Allowed     | Not Allowed | Lock on block of table |
| SERIALIZABLE              |   committed data  | Not Allowed | Not Allowed | Lock on full table     |
+---------------------------+-------------------+-------------+-------------+------------------------+

阅读感悟:出现以下3种主要问题:

脏读:从另一个tx(事务)中读取未提交的数据。 不可重复读取:从另一个tx读取已提交的更新。 幻影读取:从另一个tx读取已提交的insert和/或delete

下面的图表显示了哪个事务隔离级别可以解决哪些并发问题:

+---------------------------+--------------+----------------------+----------------+
| Isolation Level Mode      |  Dirty reads | Non-repeatable reads | Phantoms reads |
+---------------------------+--------------+----------------------+----------------+
| READ_UNCOMMITTED          | X            | X                    | X           |
| READ_COMMITTED (Default)  | solves       | X                    | X           |
| REPEATABLE_READ           | solves       | solves               | X           |
| SERIALIZABLE              | solves       | solves               | solves      |
+---------------------------+--------------+----------------------+----------------+

为例子

其他回答

You almost never want to use Read Uncommited since it's not really ACID compliant. Read Commmited is a good default starting place. Repeatable Read is probably only needed in reporting, rollup or aggregation scenarios. Note that many DBs, postgres included don't actually support Repeatable Read, you have to use Serializable instead. Serializable is useful for things that you know have to happen completely independently of anything else; think of it like synchronized in Java. Serializable goes hand in hand with REQUIRES_NEW propagation.

我对所有运行UPDATE或DELETE查询的函数以及“服务”级函数都使用require。对于只运行select的DAO级函数,我使用SUPPORTS,如果一个已经启动(即从服务函数调用),它将参与TX。

其他答案对每个参数都给出了足够的解释;但是,您要求的是一个真实世界的示例,下面是一个阐明不同传播选项的目的的示例:

Suppose you're in charge of implementing a

注册服务

in which a confirmation e-mail is sent to the user. You come up with two service objects, one for

招收

the user and one for

发送

e-mails, which the latter is called inside the first one. For example something like this:
/* Sign Up service */
@Service
@Transactional(Propagation=REQUIRED)
class SignUpService{
 ...
 void SignUp(User user){
    ...
    emailService.sendMail(User);
 }
}

/* E-Mail Service */
@Service
@Transactional(Propagation=REQUIRES_NEW)
class EmailService{
 ...
 void sendMail(User user){
  try{
     ... // Trying to send the e-mail
  }catch( Exception)
 }
}

您可能已经注意到第二个服务的传播类型为REQUIRES_NEW,而且它很可能抛出异常(SMTP服务器宕机、无效电子邮件或其他原因)。你可能不希望整个过程回滚,比如从数据库中删除用户信息或其他东西;因此,在单独的事务中调用第二个服务。

Back to our example, this time you are concerned about the database security, so you define your DAO classes this way:
/* User DAO */
@Transactional(Propagation=MANDATORY)
class UserDAO{
 // some CRUD methods
}

这意味着无论何时创建一个DAO对象,以及因此对DB的潜在访问,我们都需要确保调用是从我们的一个服务内部发出的,这意味着应该存在一个活动事务;否则会出现异常。因此,传播类型为MANDATORY。

事务表示数据库的一个工作单元。具有自己的txns(或没有txn)的多个服务中的事务行为称为事务传播。事务隔离定义了当两个事务并发作用于同一个数据库实体时的数据库状态。

TransactionDefinition接口,该接口定义了与spring兼容的事务属性。@Transactional注释描述方法或类上的事务属性。

@Autowired
private TestDAO testDAO;

@Transactional(propagation=TransactionDefinition.PROPAGATION_REQUIRED,isolation=TransactionDefinition.ISOLATION_READ_UNCOMMITTED)
public void someTransactionalMethod(User user) {

  // Interact with testDAO

}

传播(复制):用于事务间的关系。(类似于Java线程间通信)

+-------+---------------------------+------------------------------------------------------------------------------------------------------+
| value |        Propagation        |                                             Description                                              |
+-------+---------------------------+------------------------------------------------------------------------------------------------------+
|    -1 | TIMEOUT_DEFAULT           | Use the default timeout of the underlying transaction system, or none if timeouts are not supported. |
|     0 | PROPAGATION_REQUIRED      | Support a current transaction; create a new one if none exists.                                      |
|     1 | PROPAGATION_SUPPORTS      | Support a current transaction; execute non-transactionally if none exists.                           |
|     2 | PROPAGATION_MANDATORY     | Support a current transaction; throw an exception if no current transaction exists.                  |
|     3 | PROPAGATION_REQUIRES_NEW  | Create a new transaction, suspending the current transaction if one exists.                          |
|     4 | PROPAGATION_NOT_SUPPORTED | Do not support a current transaction; rather always execute non-transactionally.                     |
|     5 | PROPAGATION_NEVER         | Do not support a current transaction; throw an exception if a current transaction exists.            |
|     6 | PROPAGATION_NESTED        | Execute within a nested transaction if a current transaction exists.                                 |
+-------+---------------------------+------------------------------------------------------------------------------------------------------+

隔离:隔离是数据库事务的ACID(原子性、一致性、隔离性、持久性)属性之一。隔离决定了事务完整性如何对其他用户和系统可见。它用于资源锁定,即并发控制,确保在给定的点上只有一个事务可以访问资源。

锁定感知:隔离级别决定持有锁的持续时间。

+---------------------------+-------------------+-------------+-------------+------------------------+
| Isolation Level Mode      |  Read             |   Insert    |   Update    |       Lock Scope       |
+---------------------------+-------------------+-------------+-------------+------------------------+
| READ_UNCOMMITTED          |  uncommitted data | Allowed     | Allowed     | No Lock                |
| READ_COMMITTED (Default)  |   committed data  | Allowed     | Allowed     | Lock on Committed data |
| REPEATABLE_READ           |   committed data  | Allowed     | Not Allowed | Lock on block of table |
| SERIALIZABLE              |   committed data  | Not Allowed | Not Allowed | Lock on full table     |
+---------------------------+-------------------+-------------+-------------+------------------------+

阅读感悟:出现以下3种主要问题:

脏读:从另一个tx(事务)中读取未提交的数据。 不可重复读取:从另一个tx读取已提交的更新。 幻影读取:从另一个tx读取已提交的insert和/或delete

下面的图表显示了哪个事务隔离级别可以解决哪些并发问题:

+---------------------------+--------------+----------------------+----------------+
| Isolation Level Mode      |  Dirty reads | Non-repeatable reads | Phantoms reads |
+---------------------------+--------------+----------------------+----------------+
| READ_UNCOMMITTED          | X            | X                    | X           |
| READ_COMMITTED (Default)  | solves       | X                    | X           |
| REPEATABLE_READ           | solves       | solves               | X           |
| SERIALIZABLE              | solves       | solves               | solves      |
+---------------------------+--------------+----------------------+----------------+

为例子

隔离级别定义了一个事务对某个数据存储库所做的更改如何影响其他同时并发的事务,以及更改后的数据如何以及何时对其他事务可用。当我们使用Spring框架定义事务时,我们还可以配置在哪个隔离级别中执行同一事务。

@Transactional(isolation=Isolation.READ_COMMITTED)
public void someTransactionalMethod(Object obj) {

}

READ_UNCOMMITTED隔离级别表示事务可以读取其他事务尚未提交的数据。

READ_COMMITTED隔离级别表示事务不能读取其他事务尚未提交的数据。

REPEATABLE_READ隔离级别表示,如果一个事务多次从数据库读取一条记录,那么所有这些读取操作的结果必须始终相同。

SERIALIZABLE隔离级别是所有隔离级别中限制最严格的。事务在所有级别上(读、范围和写锁定)都是带锁执行的,因此它们看起来好像是以序列化的方式执行的。

传播是决定如何在逻辑事务或物理事务中封装业务方法的能力。

Spring REQUIRED行为意味着如果在当前bean方法执行上下文中已经打开了一个事务,那么将使用相同的事务。

REQUIRES_NEW行为意味着容器总是会创建一个新的物理事务。

NESTED行为使得嵌套Spring事务使用相同的物理事务,但是在嵌套调用之间设置保存点,这样内部事务也可以独立于外部事务回滚。

MANDATORY行为声明现有的已打开事务必须已经存在。否则容器将引发异常。

NEVER行为表示现有的已打开事务必须不存在。如果事务存在,容器将抛出异常。

NOT_SUPPORTED行为将在任何事务的作用域之外执行。如果一个打开的事务已经存在,它将被暂停。

如果已打开的事务已经存在,SUPPORTS行为将在事务范围内执行。如果没有已经打开的事务,该方法将以非事务的方式执行。

我们可以为此添加:

@Transactional(readOnly = true)
public class Banking_CustomerService implements CustomerService {

    public Customer getDetail(String customername) {
        // do something
    }

    // these settings have precedence for this method
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void updateCustomer(Customer customer) {
        // do something
    }
}