Java annotation-based
The annotation declarative approach configures the transaction attributes via annotations in the Java source file. Annotation-based declarative transaction management is more popular than XML-based because of following:
- Easier to use
- Transaction semantics close to affected Java source code making the code well documented
The steps to be followed for adding declarative transaction management to your application can be summarized using the following steps:
- Define a transaction manager in Spring configuration file (This is still required in annotation-based transaction style as well)
[xml]
[/xml]
- Turn on support for transaction annotations in your Java source code, in the Spring configuration file
[xml][/xml]
- Add the @Transactional annotation to the method defined in your service class or the service class itself
[java]@Transactional
public class LoyaltyService{
Double getLoyaltyPoints(String customerCode) {
//Some code….
}
}[/java]
@Transactional in Detail
The annotation @Transactional can be applied to a method or at the class level. If applied to a class, all the public methods within the class will inherit the @Transactional annotation. It is also possible to configure the isolation level and the propagation nature. If not specified, the propagation defaults to REQUIRED and for the isolation level, it uses the database isolation level. The various default settings can be summarized as follows:
- Isolation level is defaulted to ISOLATION_DEFAULT.
- Propagation setting is defaulted to PROPAGATION_REQUIRED.
- Transaction setting is read/write in nature.
- Any RuntimeException triggers rollback, and any checked Exception does not.
- Transaction timeout defaults to the default timeout of the underlying transaction system or to none if timeouts are not supported by the underlying transaction system.
@Transactional Settings
By default, attribute “proxy-target-class” in is set to false, such that only interfaces with @Transactional annotations are proxied. This is useful if you divide your service architecture into a service interface and an implementation. If this is not the case, it is required to set this attribute to true for class-based proxies to be created.
[xml][/xml]
@Transactional annotation has other properties which can be used to control the transaction behaviour in your services. Some of the commonly used ones are:
- readOnly
[xml]@Transactional(readOnly=true)[/xml]
- propagation
[xml]@Transactional(propagation=Propagation.REQUIRES_NEW)[/xml]
Page Visitors: 9315

Tomcy John

Latest posts by Tomcy John (see all)
- A Guide to Continuous Improvement for Architects - February 2, 2023
- Cloud-first Architecture Strategy - January 26, 2023
- Architecture Strategy and how to create One - January 24, 2023
Thanks, nice chapter.