I\'m learning about how to create REST API with JPA and Hibernate and a MySQL database and I see this @Transactional annotation. Can someone explain what is the use of this anno
The class declares @Transactional
on itself or its members, Spring creates a proxy that implements the same interface(s) as the class you’re annotating. In other words, Spring wraps the bean in the proxy and the bean itself has no knowledge of it.
A proxy provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied.
Internally, its the same as using a transaction advice (using AOP), where a proxy is created first and is invoked before/after the target bean’s method.
The generated proxy object is supplied with a TransactionInterceptor
, which is created by Spring. So when the @Transactional
method is called from client code, the TransactionInterceptor
gets invoked first from the proxy object, which begins the transaction and eventually invokes the method on the target bean. When the invocation finishes, the TransactionInterceptor
commits/rolls back the transaction accordingly