Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The business Transaction thing.

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Transaction is the so-called business, popular understanding is one thing. From an early age, our parents taught us to do things from the beginning to the end, not to give up halfway. The same is true of affairs. If you don't do it, you can either finish it or don't do it. In other words, affairs must be an indivisible whole, just like the atoms we learned in chemistry, the atoms are the smallest units that make up matter. As a result, people sum up the first characteristic of a transaction: Atomicity. Shit, it's not mysterious at all.

Especially in the database field, transaction is a very important concept, in addition to atomicity, it also has an extremely important feature, that is: Consistency. In other words, after performing the database operation, the data will not be corrupted. For example, if you transfer money from An account to B account, it is impossible to deduct money from An account and not add money to B account. If this kind of thing happens, you will be very angry, what diao bank ah!

When we write a update statement and submit it to the database, it is possible that someone else also submitted a delete statement to the database. Maybe we all operate on the same record, and we can imagine that if we don't control it a little bit, it will be annoying. We must ensure that database operations are "isolated" (and sometimes threads are isolated) without any interference with each other. This is: Isolation.

It is very difficult to really achieve that there is no interference between operations, so database experts who go to work every day begin to use their brains, "We need to develop a specification." let all database vendors support our specification! " The specification is: transaction isolation level (Transaction Isolation Level) It's not easy to define such a powerful specification, but to put it bluntly, there are only four levels:

READ_UNCOMMITTED

READ_COMMITTED

REPEATABLE_READ

SERIALIZABLE

Never translate, it's just a code name. From top to bottom, the level is getting higher and higher, the concurrency is getting worse, and the security is getting higher and higher, and vice versa.

When we execute an insert statement, the database must ensure that a piece of data is permanently stored on disk, which is also a feature of the transaction: Durability.

To sum up, the above mentioned a total of four transaction features, their English word initials together is: ACID, this is the legendary "transaction ACID feature"!

It's really a very powerful feature! These four features are the cornerstone of transaction management and must be thoroughly understood. In addition, it should be clear that among these four guys, who is the boss?

In fact, it is clear when you think about it: atomicity is the foundation, isolation is the means, persistence is the end, and the real boss is consistency. If the data are inconsistent, it is equivalent to "rivers and lakes are in a mess, and hooligans wear bras." Therefore, these three younger brothers all follow the boss of "consistency" to serve him wholeheartedly.

In fact, the most difficult thing to understand among these four guys is not consistency, but isolation. Because it is an important means to ensure consistency, is a tool, there can be no difference in using it, otherwise you will bear the consequences! No wonder database industry experts have come to study the so-called transaction isolation level. In fact, these four levels are defined to solve the problems caused by high concurrency of data, so what are the problems?

Dirty Read (dirty reading)

Unrepeatable Read (non-repeatable)

Phantom Read (Phantom Reading)

First of all, take a look at "dirty reading". When I see the word "dirty", I think of disgusting and dirty. How can the data be dirty? In fact, it is what we often call "junk data". For example, there are two transactions that are executing concurrently (that is, competing). If you look at the following table, you will surely understand what I am talking about:

The balance should be 1500 yuan! Please take a look at the T5 time point, transaction An at this time the query balance is 0 yuan, this data is dirty data, it is caused by transaction B, obviously the transaction is not isolated, seeping through, messy.

Therefore, the matter of dirty reading is very undesirable and must be solved! Isolating transactions is the last word.

How to interpret Article 2, which can not be read repeatedly? Or use similar examples to illustrate:

In fact, transaction A didn't do anything except twice. As a result, the money changed from 1000 to 0, which is repeated reading. It is conceivable that someone else did this, not me. In fact, this is also reasonable, after all, transaction B commits the transaction, and the database persists the result, so transaction A reads again and naturally changes.

This phenomenon is basically understandable, but it is not allowed in some abnormal situations. After all, this phenomenon is also caused by the lack of isolation between transactions, but we seem to be able to ignore this problem.

The last one, hallucination. WTF! Isn't the word Phantom "ghost, ghost"? When I first saw this word, I really stunned my little brother. No wonder it has to be translated into "phantom reading", but not "ghost reading" or "ghost reading". In fact, the meaning is that ghosts are reading, not people are reading, or do not know why, it has changed, very dizzy, really dizzy. Let's use an example to speak:

Each time the bank staff counted the total deposits, they saw different results. However, this is also quite normal, the total deposit has increased, someone must be saving money at this time. But if the banking system is really designed this way, it's over. This is also caused by the lack of transaction isolation, but for most applications, this also seems normal, understandable, and permissible. The disgusting systems in the bank are so strict that when counting, they even isolate all other operations, which is a very high level of isolation (probably to the SERIALIZABLE level).

To sum up, the problems related to reading data caused by transaction concurrency mentioned above are described in one sentence:

Dirty reading: transaction A reads the uncommitted data of transaction B and does other operations on that basis.

Unrepeatable: transaction A reads the change data that transaction B has committed.

Illusion: transaction A reads the new data that transaction B has committed.

The first one is resolutely resisted, and the latter two are not considered in most cases.

That's why there has to be a transaction isolation level, which is like a wall, isolating different transactions. Take a look at the following table to see what kind of transaction concurrency problems can be handled by different transaction isolation levels:

According to your actual needs, refer to this table and finally determine the transaction isolation level, which should no longer be a difficult task.

JDBC also provides these four types of transaction isolation levels, but the default transaction isolation levels are different for different database products. The default transaction isolation level for familiar MySQL databases is that READ_COMMITTED,Oracle, SQL Server, DB2, and so on all have their own default values. I think READ_COMMITTED can already solve most of the problems. Let's analyze the rest on a case-by-case basis.

If you are not clear about the default transaction isolation level for other databases, you can use the following code to get:

DatabaseMetaData meta = DBUtil.getDataSource (). GetConnection (). GetMetaData ()

Int defaultIsolation = meta.getDefaultTransactionIsolation ()

Tip: all isolation levels can be viewed in the java.sql.Connection class.

We know that JDBC is just a bridge between Java programs and databases, so how does the database isolate transactions? In fact, it is the "lock" this thing. When you insert data, you lock the table, which is called "locking the table"; when you update the data, you lock the row, which is called "locking the row." Of course, this is beyond the scope of our discussion today, so let's leave some space for our DBA classmate, in case he has nothing to write about.

Apart from the transaction isolation level solution provided to us by JDBC, what other solutions can improve the transaction management capabilities?

Take a look at Spring's solution, which is actually a supplement or extension to JDBC. It provides a very important function: transaction propagation behavior (Transaction Propagation Behavior).

Really good enough, Spring suddenly provided 7 kinds of transaction communication behavior, these 7 kinds of behavior appeared, really blinded my dog's eyes!

PROPAGATION_REQUIRED

RROPAGATION_REQUIRES_NEW

PROPAGATION_NESTED

PROPAGATION_SUPPORTS

PROPAGATION_NOT_SUPPORTED

PROPAGATION_NEVER

PROPAGATION_MANDATORY

After reading the Spring reference manual, I feel even more dizzy. What on earth are you doing?

The first thing to be clear is, where does the business come from? Where does it spread? The answer is to propagate from method A to method B. Spring only deals with transaction propagation between methods, so there are many cases, such as:

Method A has transactions, and method B also has transactions.

Method A has transactions and method B has no transactions.

Method A has no transaction, method B has transaction.

Method A has no transactions, and method B has no transactions.

That's four, and there are three special cases. Let's use my Style to give you an analysis:

Assuming that the transaction propagates from method A to method B, you need to face method B and ask yourself a question:

Is there a transaction in method A?

If not, create a new transaction; if so, join the current transaction. This is PROPAGATION_REQUIRED, which is also the default transaction propagation behavior provided by Spring and is suitable for most situations.

If not, create a new transaction; if so, suspend the current transaction. This is RROPAGATION_REQUIRES_NEW, which means that a new transaction is created, which has nothing to do with the original transaction.

If not, create a new transaction; if so, nest other transactions in the current transaction. This is PROPAGATION_NESTED, the legendary "nested transaction", in which the nested sub-transaction is associated with the main transaction (when the main transaction commits or rolls back, the sub-transaction commits or rolls back).

If not, it is executed in a non-transactional manner; if so, the current transaction is used. This is PROPAGATION_SUPPORTS, this way is very casual, no, there is no, there is, a little indifferent attitude, anyway, I support you.

If not, execute in a non-transactional manner; if so, suspend the current transaction. This is PROPAGATION_NOT_SUPPORTED, this way is very tough, there is no, there is no, I do not support you, hang you up, do not bird you.

If not, it is executed in a non-transactional manner; if so, an exception is thrown. This is PROPAGATION_NEVER, this way is more fierce, there is no, there is no, instead of reporting a mistake, it is really awesome, it says: I never support affairs!

If not, an exception is thrown; if so, the current transaction is used. This is PROPAGATION_MANDATORY, this way can be said to be the most powerful, there is no transaction to report mistakes directly, it is really ruthless, it says: I must have affairs!

Seeing my explanation above, do my friends already feel the feeling of being connected to the governor's second pulse? Read it a few more times and experience it. It's your own stuff.

It is important to note that PROPAGATION_NESTED, do not be fooled by its name, Nested (nested), so whenever you use this kind of transaction propagation behavior on method B when calling method B like method A, if you do do that, you are wrong. Because you mistakenly think that PROPAGATION_NESTED is prepared for method nested calls, the default PROPAGATION_REQUIRED can help you do what you want to do.

Spring brings us transaction propagation behavior, which is indeed a very powerful and practical feature. In addition, some small additional features are provided, such as:

1 transaction timeout (Transaction Timeout): in order to solve the problem that the transaction takes too long and consumes too many resources, the transaction is deliberately set a maximum time, and if it is exceeded, the transaction is rolled back.

Read-only transactions (Readonly Transaction): in order to ignore methods that do not require transactions, such as reading data, this can effectively improve some performance.

Finally, it is recommended that you use Spring's annotated transaction configuration instead of XML transaction configuration. Because annotations are so elegant, of course it all depends on your own situation.

Use in the Spring configuration file:

...

...

Use on methods that require transactions:

Transactional

Public void xxx () {

...

}

Can be set in the @ Transactional annotation: transaction isolation level, transaction propagation behavior, transaction timeout, whether read-only transactions.

It's perfect, so elegant!

Finally, it is necessary to make a summary of the content of this article, giving away a free high-definition no-code mind map:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report