声明性事务范围
Spring和JPA @Transaction注释都允许您定义给定应用程序事务的范围。
因此,如果使用@Transactional注释注释了一个服务方法,那么它将在事务上下文中运行。如果服务方法使用多个DAO或存储库,则所有读和写操作都将在同一个数据库事务中执行。
Spring @ transactional
transactional注释从Spring框架的1.2版本(大约在2005年)开始就可用了,它允许你设置以下事务属性:
isolation: the underlying database isolation level
noRollbackFor and noRollbackForClassName: the list of Java Exception classes that can be triggered without triggering a transaction rollback
rollbackFor and rollbackForClassName: the list of Java Exception classes that trigger a transaction rollback when being thrown
propagation: the transaction propagation type given by the Propagation Enum. For instance, if the transaction context can be inherited (e.g., REQUIRED) or a new transaction context should be created (e.g., REQUIRES_NEW) or if an exception should be thrown if no transaction context is present (e.g., MANDATORY) or if an exception should be thrown if a current transaction context is found (e.g., NOT_SUPPORTED).
readOnly: whether the current transaction should only read data without applying any changes.
timeout: how many seconds should the transaction context be allowed to run until a timeout exception is thrown.
value or transactionManager: the name of the Spring TransactionManager bean to be used when binding the transaction context.
Java EE @事务性
javax.transaction.Transactional注释是由Java EE 7规范(大约2013年)添加的。因此,Java EE注释比Spring注释晚添加了8年。
Java EE @Transactional只定义了3个属性:
dontRollbackOn: the list of Java Exception classes that can be triggered without triggering a transaction rollback
rollbackOn: the list of Java Exception classes that trigger a transaction rollback when being thrown
value: the propagation strategy, given by the TxType Enum. For instance, if the transaction context can be inherited (e.g., REQUIRED) or a new transaction context should be created (e.g., REQUIRES_NEW) or if an exception should be thrown if no transaction context is present (e.g., MANDATORY) or if an exception should be thrown if a current transaction context is found (e.g., NOT_SUPPORTED).
选择哪一个?
如果您正在使用Spring或Spring Boot,那么请使用Spring @Transactional注释,因为它允许您配置比Java EE @Transactional注释更多的属性。
如果您单独使用Java EE,并且将应用程序部署在Java EE应用服务器上,那么请使用Java EE @Transactional注释。