Penyebaran dan Pengasingan Transaksi pada Musim Bunga @Transactional

1. Pengenalan

Dalam tutorial ini, kita akan membahas anotasi @Transactional dan tetapan pengasingan dan penyebarannya .

2. Apa itu @Transactional?

Kita boleh menggunakan @Transactional untuk membungkus kaedah dalam transaksi pangkalan data.

Ini membolehkan kita menetapkan syarat penyebaran, pengasingan, waktu tunggu, baca sahaja, dan penggantian untuk transaksi kita. Kita juga boleh menentukan pengurus transaksi.

2.1. @ Perincian Pelaksanaan Transaksional

Spring membuat proksi atau memanipulasi kod byte kelas untuk mengurus pembuatan, komit, dan penggantian transaksi. Sekiranya proksi, Spring mengabaikan @Transactional dalam panggilan kaedah dalaman.

Ringkasnya, jika kita mempunyai kaedah seperti callMethod dan kita menandainya sebagai @Transactional, Spring akan membungkus beberapa kod pengurusan transaksi di sekitar permintaan: Kaedah @Transactional disebut:

createTransactionIfNecessary(); try { callMethod(); commitTransactionAfterReturning(); } catch (exception) { completeTransactionAfterThrowing(); throw exception; }

2.2. Cara Menggunakan @Transactional

Kita boleh meletakkan penjelasan pada definisi antara muka, kelas, atau secara langsung pada kaedah. Mereka saling mengatasi mengikut urutan keutamaan; dari terendah ke tertinggi yang kita ada: Antaramuka, superclass, kelas, kaedah antara muka, kaedah superclass, dan kaedah kelas.

Spring menerapkan anotasi peringkat kelas untuk semua kaedah umum kelas ini yang tidak kami beri anotasi dengan @Transactional .

Namun, jika kita meletakkan anotasi pada kaedah peribadi atau dilindungi, Spring akan mengabaikannya tanpa kesalahan.

Mari kita mulakan dengan contoh antara muka:

@Transactional public interface TransferService { void transfer(String user1, String user2, double val); } 

Biasanya, tidak digalakkan untuk menetapkan @Transactional pada antara muka. Walau bagaimanapun, ia boleh diterima untuk kes seperti @Repository dengan Spring Data.

Kami dapat meletakkan anotasi pada definisi kelas untuk mengatasi tetapan transaksi antara muka / superclass:

@Service @Transactional public class TransferServiceImpl implements TransferService { @Override public void transfer(String user1, String user2, double val) { // ... } }

Sekarang mari kita ganti dengan menetapkan anotasi secara langsung pada kaedah:

@Transactional public void transfer(String user1, String user2, double val) { // ... }

3. Penyebaran Transaksi

Penyebaran menentukan had transaksi logik perniagaan kami. Spring berjaya memulakan dan menjeda transaksi mengikut tetapan penyebaran kami .

Spring memanggil TransactionManager :: getTransaction untuk mendapatkan atau membuat transaksi mengikut penyebaran. Ini mendukung beberapa penyebaran untuk semua jenis TransactionManager , tetapi ada beberapa di antaranya yang hanya didukung oleh implementasi tertentu dari TransactionManager .

Sekarang mari kita lihat penyebaran yang berbeza dan bagaimana ia berfungsi.

3.1. DIPERLUKAN Penyebaran

DIPERLUKAN adalah penyebaran lalai. Spring memeriksa jika ada transaksi yang aktif, maka ia akan membuat transaksi baru jika tidak ada. Jika tidak, logik perniagaan melampirkan pada transaksi yang sedang aktif:

@Transactional(propagation = Propagation.REQUIRED) public void requiredExample(String user) { // ... }

Juga kerana DIPERLUKAN adalah penyebaran lalai, kita dapat mempermudah kod dengan menjatuhkannya:

@Transactional public void requiredExample(String user) { // ... }

Mari lihat kod pseudo bagaimana penciptaan transaksi berfungsi untuk penyebaran yang DIPERLUKAN :

if (isExistingTransaction()) { if (isValidateExistingTransaction()) { validateExisitingAndThrowExceptionIfNotValid(); } return existing; } return createNewTransaction();

3.2. Penyebaran SOKONGAN

Untuk SOKONGAN , Spring memeriksa terlebih dahulu jika ada transaksi aktif. Sekiranya transaksi ada, maka transaksi yang ada akan digunakan. Sekiranya tidak ada urus niaga, ia akan dilakukan tanpa transaksi:

@Transactional(propagation = Propagation.SUPPORTS) public void supportsExample(String user) { // ... }

Mari lihat kod pseudo pembuatan transaksi untuk SOKONGAN :

if (isExistingTransaction()) { if (isValidateExistingTransaction()) { validateExisitingAndThrowExceptionIfNotValid(); } return existing; } return emptyTransaction;

3.3. Penyebaran MANDATORI

Apabila penyebaran itu MANDATORI , jika ada transaksi aktif, maka ia akan digunakan. Sekiranya tidak ada transaksi yang aktif, maka Spring akan membuat pengecualian:

@Transactional(propagation = Propagation.MANDATORY) public void mandatoryExample(String user) { // ... }

Dan mari kita lihat lagi kod pseudo:

if (isExistingTransaction()) { if (isValidateExistingTransaction()) { validateExisitingAndThrowExceptionIfNotValid(); } return existing; } throw IllegalTransactionStateException;

3.4. PERNAH PERBEZAAN

Untuk logik transaksi dengan penyebaran TIDAK PERNAH , Spring memberikan pengecualian sekiranya terdapat transaksi yang aktif:

@Transactional(propagation = Propagation.NEVER) public void neverExample(String user) { // ... }

Mari lihat kod pseudo bagaimana penciptaan transaksi berfungsi untuk PERNAH menyebarkan:

if (isExistingTransaction()) { throw IllegalTransactionStateException; } return emptyTransaction;

3.5. NOT_SUPPORTED Propagation

Spring at first suspends the current transaction if it exists, then the business logic is executed without a transaction.

@Transactional(propagation = Propagation.NOT_SUPPORTED) public void notSupportedExample(String user) { // ... }

The JTATransactionManager supports real transaction suspension out-of-the-box. Others simulate the suspension by holding a reference to the existing one and then clearing it from the thread context

3.6. REQUIRES_NEW Propagation

When the propagation is REQUIRES_NEW, Spring suspends the current transaction if it exists and then creates a new one:

@Transactional(propagation = Propagation.REQUIRES_NEW) public void requiresNewExample(String user) { // ... }

Similar to NOT_SUPPORTED, we need the JTATransactionManager for actual transaction suspension.

And the pseudo-code looks like so:

if (isExistingTransaction()) { suspend(existing); try { return createNewTransaction(); } catch (exception) { resumeAfterBeginException(); throw exception; } } return createNewTransaction();

3.7. NESTED Propagation

For NESTED propagation, Spring checks if a transaction exists, then if yes, it marks a savepoint. This means if our business logic execution throws an exception, then transaction rollbacks to this savepoint. If there's no active transaction, it works like REQUIRED .

DataSourceTransactionManager supports this propagation out-of-the-box. Also, some implementations of JTATransactionManager may support this.

JpaTransactionManager supports NESTED only for JDBC connections. However, if we set nestedTransactionAllowed flag to true, it also works for JDBC access code in JPA transactions if our JDBC driver supports savepoints.

Finally, let's set the propagation to NESTED:

@Transactional(propagation = Propagation.NESTED) public void nestedExample(String user) { // ... }

4. Transaction Isolation

Isolation is one of the common ACID properties: Atomicity, Consistency, Isolation, and Durability. Isolation describes how changes applied by concurrent transactions are visible to each other.

Each isolation level prevents zero or more concurrency side effects on a transaction:

  • Dirty read: read the uncommitted change of a concurrent transaction
  • Nonrepeatable read: get different value on re-read of a row if a concurrent transaction updates the same row and commits
  • Phantom read: get different rows after re-execution of a range query if another transaction adds or removes some rows in the range and commits

We can set the isolation level of a transaction by @Transactional::isolation. It has these five enumerations in Spring: DEFAULT, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE.

4.1. Isolation Management in Spring

The default isolation level is DEFAULT. So when Spring creates a new transaction, the isolation level will be the default isolation of our RDBMS. Therefore, we should be careful if we change the database.

We should also consider cases when we call a chain of methods with different isolation. In the normal flow, the isolation only applies when a new transaction created. Thus if for any reason we don't want to allow a method to execute in different isolation, we have to set TransactionManager::setValidateExistingTransaction to true. Then the pseudo-code of transaction validation will be:

if (isolationLevel != ISOLATION_DEFAULT) { if (currentTransactionIsolationLevel() != isolationLevel) { throw IllegalTransactionStateException } }

Now let's get deep in different isolation levels and their effects.

4.2. READ_UNCOMMITTED Isolation

READ_UNCOMMITTED is the lowest isolation level and allows for most concurrent access.

As a result, it suffers from all three mentioned concurrency side effects. So a transaction with this isolation reads uncommitted data of other concurrent transactions. Also, both non-repeatable and phantom reads can happen. Thus we can get a different result on re-read of a row or re-execution of a range query.

We can set the isolation level for a method or class:

@Transactional(isolation = Isolation.READ_UNCOMMITTED) public void log(String message) { // ... }

Postgres does not support READ_UNCOMMITTED isolation and falls back to READ_COMMITED instead. Also, Oracle does not support and allow READ_UNCOMMITTED.

4.3. READ_COMMITTED Isolation

The second level of isolation, READ_COMMITTED, prevents dirty reads.

The rest of the concurrency side effects still could happen. So uncommitted changes in concurrent transactions have no impact on us, but if a transaction commits its changes, our result could change by re-querying.

Here, we set the isolation level:

@Transactional(isolation = Isolation.READ_COMMITTED) public void log(String message){ // ... }

READ_COMMITTED is the default level with Postgres, SQL Server, and Oracle.

4.4. REPEATABLE_READ Isolation

The third level of isolation, REPEATABLE_READ, prevents dirty, and non-repeatable reads. So we are not affected by uncommitted changes in concurrent transactions.

Also, when we re-query for a row, we don't get a different result. But in the re-execution of range-queries, we may get newly added or removed rows.

Moreover, it is the lowest required level to prevent the lost update. The lost update occurs when two or more concurrent transactions read and update the same row. REPEATABLE_READ does not allow simultaneous access to a row at all. Hence the lost update can't happen.

Here is how to set the isolation level for a method:

@Transactional(isolation = Isolation.REPEATABLE_READ) public void log(String message){ // ... }

REPEATABLE_READ is the default level in Mysql. Oracle does not support REPEATABLE_READ.

4.5. SERIALIZABLE Isolation

SERIALIZABLE is the highest level of isolation. It prevents all mentioned concurrency side effects but can lead to the lowest concurrent access rate because it executes concurrent calls sequentially.

In other words, concurrent execution of a group of serializable transactions has the same result as executing them in serial.

Now let's see how to set SERIALIZABLE as the isolation level:

@Transactional(isolation = Isolation.SERIALIZABLE) public void log(String message){ // ... }

5. Conclusion

In this tutorial, we explored the propagation property of @Transaction in detail. Afterward, we learned about concurrency side effects and isolation levels.

As always, you can find the complete code over on GitHub.