Two issues related to spring transactions
Some spring-related knowledge points have not been carefully studied before: for example, spring transactions are not unused, it was also simple to add transaction annotations to implement transaction functions in some methods that require transaction processing, just to follow the use (or even not to test the correctness of the transaction ), as for how to configure transactions in the project, how can we write the transactions correctly? Other principles of transactions have never taken time to study. Recently, my colleague threw out a question and took this opportunity to learn it again.
Question 1: Added the readOnly = true transaction to include write operations. Why is this code running online normal?
@Transactional(readOnly = true) public Integer getUID(String key, String type) { keyGeneratorDao.insert(key, type); keyGeneratorDao.update(key, type); return keyGeneratorDao.select(key, type); }
Why am I interested in this question?
- Do not understand the meaning of this readOnly parameter. If you write @ Transactional annotation before, it is the default value used, without the display parameter.
- After the readOnly parameter is configured, the program should theoretically report an error, but there is actually no error, to find out why.
Start write unit test:
- Write transaction functions and test methods in unit test classes
@Autowired private IkeyGeneratorDao keyGeneratorDao; @Transactional(readOnly=true) public Integer getId(String key, String type){ return keyGeneratorDao.select(key, type); } @Transactional public Integer getUID(String key, String type) { keyGeneratorDao.insert(key, type); keyGeneratorDao.update(key, type); return this.getId(key,type); } @Test public void testCreateGuid(){ int guid=this.getUID("12345", "jim"); System.out.println(guid); }
The test results show that they are normal, which is the opposite of the above-mentioned idea of not allowing write operations. This reminds me of the typical transaction effectiveness problem.
The first pitfall: If the transaction uses cglib dynamic proxy, the called method and the transaction method are in the same class and the transaction method does not take effect.
- Transfer two transaction transactions to a separate class, and then test that the class code is omitted. The above two methods marked with @ Transactional are encapsulated in a separate class.
@Autowired private KeyGeneratorService keyService; @Test public void testCreateGuid2(){ int guid=this.keyService.getUID("12345", "jim"); System.out.println(guid); }
The test result is also normal, so I want to check whether the transaction has taken effect and add an exception to test whether the data is rolled back. The modification code is as follows:
@Transactional public Integer getUID3(String key, String type) { keyGeneratorDao.insert(key, type); Integer.parseInt("aaa");//throw exception keyGeneratorDao.update(key, type);}
The test results show that the transaction rollback is normal and the transaction environment configuration can be ruled out.
The second pitfall:The test must be as consistent as possible with the original problem code. Otherwise, other unknown causes may occur. By comparing the code of the original problem, we found that the test code I wrote is different from the problem code. readOnly is added to the methods that contain write operations, while I use two methods, only readOnly is added to the reading method, and the code is modified again:
@Transactional(readOnly = true) public Integer getUID4(String key, String type) { keyGeneratorDao.insert(key, type); keyGeneratorDao.update(key, type); return keyGeneratorDao.select(key, type); }
The test result shows that the operation is abnormal and the following error is prompted: Cause: java. SQL. SQLException: Connection is read-only. queries leading to data modification are not allowed. It does indicate that write operations are not allowed in transactions with readOnly = true added. Why is this code running successfully online? Check the frontend call at the time and find that the frontend call does not directly identify the Transactional method, instead, we need to repackage the data according to different services. For example, we need to generate the order number. The front-end only calls genOrderCode and does not call getUID.
- The non-transaction method calls this transaction method internally, and the non-transaction method is called externally.
- Service
- GenOrderCode is a non-transactional method that calls the getUID internally.
- GetUID is a transaction method.
@Autowired private IkeyGeneratorDao keyGeneratorDao; @Transactional(readOnly = true) public Integer getUID(String key, String type) { keyGeneratorDao.insert(key, type); keyGeneratorDao.update(key, type); return keyGeneratorDao.select(key, type); } public String genOrderCode(Date orderDate) { SimpleDateFormat df = new SimpleDateFormat("yyMMddHH"); String ticketDate = df.format(orderDate); Integer uid = getUID(ticketDate, ORDER_CODE); return ticketDate + genRandom2(uid.toString(), 3, 3) ; }
-
- Test, external class calls non-transaction method
@Test public void testCreateGuid3(){ String guid=this.keyService.genOrderCode(new Date()); System.out.println(guid); }
The test results are normal, which is the same as the results of online operation. I was reminded by my colleagues later that this is another case of incorrect use of transactions.
The third pitfall:When a non-transaction method of a class is called and the non-transaction method internally calls the transaction method of the class, the transaction will not take effect.
Question 2:Can the following code implement transaction rollback?
- Service
- GenOrderCode method call getUID2
- Both methods have the same transaction parameters.
- GetUID2 throws an exception
- GenOrderCode caught this exception
@Transactional public Integer getUID2(String key, String type) { keyGeneratorDao.insert(key, type); Integer.parseInt("aaa");//throw exception keyGeneratorDao.update(key, type); return keyGeneratorDao.select(key, type); } @Transactional public String genOrderCode(Date orderDate) { try{ SimpleDateFormat df = new SimpleDateFormat("yyMMddHH"); String ticketDate = df.format(orderDate); Integer uid = getUID2(ticketDate, ORDER_CODE); return ticketDate + genRandom2(uid.toString(), 3, 3) ; }catch(Exception ex){ System.out.println(ex); } return null; }
@Test public void testCreateGuid3(){ String guid=this.keyService.genOrderCode(new Date()); System.out.println(guid); }
Run the test code and find that the code can be submitted successfully, but the data is incomplete because the update operation is not completed. Why? Because the default Propagation. REQUIRED indicates that multiple operations are in one transaction. Because genOrderCode has an exception, even if an exception occurs in getUID2, the system determines that the submission is legal, therefore, the insertion Operation is normal, but the normal commit of the transaction is not rolled back.
What if the specified Propagation. REQUIRES_NEW is displayed?
@Transactional(propagation=Propagation.REQUIRES_NEW) public Integer getUID2(String key, String type) { keyGeneratorDao.insert(key, type); Integer.parseInt("aaa");//throw exception keyGeneratorDao.update(key, type); return keyGeneratorDao.select(key, type); }
Perform the same test and the data is rolled back normally. Here we provide two images for you to see clearly (because of these two commonly used images, you can study them more if you are interested)
Through the two small issues in the transaction, we can summarize some tips or experience for solving the problem: do not limit the problem to a certain point after discovering the problem. It is best to combine the analysis based on context and context, for example, the readonly of Question 1 can be written, but it is difficult to find a reasonable explanation of the Code. The root cause can be found only when it is combined with the frontend and backend calls. Write unit tests to write the same code as much as possible. Otherwise, some interference items may affect the judgment. Learning, there is time to learn as much as possible, such as the @ Transactional annotation, in addition to readOnly and Propagation.