Spring transaction management

Add @Transactional before the service class to declare that all methods of this service require transaction management. A transaction is opened at the beginning of each business method.

Spring rolls back transactions by default for runtime exceptions (RunTimeException). This exception is unchecked. If it encounters a checked accident, it will not roll back.

 

How to change the default rules:

1 Make checked exceptions also rollback: add @Transactional(rollbackFor=Exception.class) before the entire method

2 Make unchecked exceptions not rolled back: @Transactional(notRollbackFor=RunTimeException.class)

3 (query-only) methods that do not require transaction management: @Transactional(propagation=Propagation.NOT_SUPPORTED)

4 If you do not add properties such as rollbackFor, Spring will roll back when Unchecked Exceptions are encountered, not only RuntimeException, but also Error.

 

important point: 

1. The method for the @Transactional annotation to work must be a public type

2. The method must throw an exception. If the exception is caught by try{}catch{}, the transaction will not be rolled back. If you want the transaction to be rolled back, you must throw try{}catch{throw Exception}.

3. The choice of mysql database type (InnoDB) 

4. The Controller layer only supports @Transactional annotation transactions!

5. In addition, if the transaction is not specified in the outermost method, it will be invalid. For example, the createAndDownloadData() method of the InventoryService class is called in the InventoryController, and the createInfo() method is called in the createAndDownload() method. In fact, a transaction needs to be done. The content of the control is in the createInfo() method, but if the @Transactional annotation is added to the createInfo() method, the transaction will not take effect; while @Transactional is added to the createAndDownload() method, the transaction will take effect normally.

 

http://www.cnblogs.com/cangqiongbingchen/p/5806972.html

 

Guess you like

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