Transaction transaction (lock data row-1)

Reference post: http://blog.csdn.net/winy_lm/article/details/50403264

 

For example: Suppose there is a quantity in the product form products that stores the number of products. Before the order is established, it must be determined whether the quantity of products is sufficient (quantity>0),

Then update the number to 1.

Unsafe practice:

SELECT quantity FROM products WHERE id=3;

UPDATE products SET quantity = 1 WHERE id=3;

Why is it not safe?

There may not be a problem in a small number of cases, but a large amount of data access will "definitely" have problems.

If we need to deduct inventory when quantity>0 It has become 0, but the program doesn't know it, and the wrong UPDATE goes on.

Therefore, the transaction mechanism must be used to ensure that the data read and submitted are correct.

practical testing:




After loading for a long time as follows


 

 

 

 

 

Test in the project:

Xml:





 
 
 

Service:



 

There is no need to write SET AUTOCOMMIT=0; BEGIN WORK; just add for update after the query statement in the project

Because @Transactional has already done this for us

Controller:



 

testing method

         The same project is started in two Tomcats. Because the breakpoint needs to be broken in one of the methods, it needs to be operated in two eclipses or packaged as a war package and put into Tomcat/webapps to start. At the same time, two Tomcats need to be changed. A port number avoids the problem of port number occupation.

         After both projects are opened, the following is the official start of the test.

When the stock is low, the display of two items:



 




 
 

 

 

When the inventory is 1, one of them enters the method breakpoint, and the other does the same:



 

Put a breakpoint on this 8081 , and the breakpoint is after findById (for update )



 

Then enter 8080 and find that the 8081 breakpoint is not released, and it has been loading here. .



 

After releasing the breakpoint, the 8081 inventory-1  succeeded, and the 8080 was also loaded, indicating that the inventory was insufficient, which met our requirements. 



 

 

Write it after:

Test the effect after removing the @Transactional annotation, and finally display "Inventory-1: success" under the same operation,
This is because without the Transactional annotation, there is no effect of SET AUTOCOMMIT=0; BEGIN WORK;,
As a result, select..for update does not take effect.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326220024&siteId=291194637