Spring transaction failure

0x01: If the database does not support transactions, it will fail
because the transaction is acting on the database. For example, if you use MySQL and the engine is MyISAM, the transaction will not work because the MyISAM engine itself does not support transactions; if you change to InnoDB, you can.

0x02: The Service class is not managed by Spring.
Because Spring's transactions are based on AOP, if the Service class is not managed by Spring, it becomes a Spring Bean. Even if the @Transactional annotation is added, the transaction is invalid.

0x03: Internal call
The method without transaction calls the method with transaction in this class, and will not be rolled back. Because Spring's rollback is generated using the proxy mode, if it is a method without a transaction to call the method with a transaction of this class, it is called directly through this.xxx () without generating a proxy transaction, so the transaction does not work . Common solutions are "declassification".

@Service
public
 
class
 
OrderServiceImpl
 
implements
 
OrderService
 
{

    
public
 
void
 update
(
Order
 order
)
 
{
        updateOrder
(
order
);
    
}

    
@Transactional
    
public
 
void
 updateOrder
(
Order
 order
)
 
{
        
// update order
    
}

}

0x04: Use the default transaction processing method

The Spring transaction defaults to rollback of RuntimeException, and does not inherit RuntimeException without rollback. Because in the design of java, it thinks that exceptions that do not inherit RuntimeException are CheckException or ordinary exceptions, such as IOException, these exceptions are required to be handled in Java syntax. For these common exceptions, Spring defaults that they have been handled, so the default is not to roll back. You can add rollbackfor = Exception.class to indicate that all Exceptions are rolled back.

0x05: Transactions can only be applied to public methods.
@Transactional annotations can only be applied to public methods. If you use @Transactional annotations on protected, private, or default visibility methods, this will be ignored and no exceptions will be thrown.

0x06: The data source is not configured with a transaction manager


// 其中 dataSource 框架会自动为我们注入
    
@Bean
    
public
 
PlatformTransactionManager
 txManager
(
DataSource
 dataSource
)
 
{
        
return
 
new
 
DataSourceTransactionManager
(
dataSource
);
    
}

If you want to use transactions, the transaction manager is not configured and the others are all in vain.

Published 17 original articles · Likes0 · Visits 224

Guess you like

Origin blog.csdn.net/weixin_42531204/article/details/104932363