Sunday, October 27, 2013


20 
21        PlatformTransactionManager transactionManager = (PlatformTransactionManager)context.getBean("transactionManager");
22        service.setTransactionManager(transactionManager);
23 
24        service.bookTicket(112);
25    }
26}
The client application loads the context for getting a reference to transaction Manager and data source objects which is given below,
1"mySqlDataSource" destroy-method="close">
2        "driverClassName" value="com.mysql.jdbc.Driver"/>
3        "url" value="jdbc:mysql://localhost/test"/>
4        "username" value="root"/>
5        "password" value="mother"/>
6    
7 
8    "transactionManager">
9        "dataSource" ref="mySqlDataSource" />
10    
Transaction Management through Annotations
In this section, we will see how to manage transactions declaratively using Spring’s annotations
Ticket Booking Service
TicketBookingServiceThroughAnnotation.java
1package net.javabeat.spring.articles.txn.ticbook.annotation;
2 
3import net.javabeat.spring.articles.txn.BookingService;
4import net.javabeat.spring.articles.txn.TicketUtils;
5 
6import org.springframework.jdbc.core.support.JdbcDaoSupport;
7import org.springframework.transaction.annotation.Transactional;
8 
9public class TicketBookingServiceThroughAnnotation extends JdbcDaoSupportimplements BookingService{
10 
11    @Transactional
12    public void bookTicket(int userId, int ticketId, int noOfTickets){
13 
14        int accountId = TicketUtils.getAccountId(getJdbcTemplate(), userId);
15 
16        float ticketCost = TicketUtils.findTicketCost(getJdbcTemplate(), ticketId);
17        float totalCost = (noOfTickets * ticketCost);
18 
19        TicketUtils.deductMoneyFromAccount(getJdbcTemplate(), accountId, totalCost);
20        TicketUtils.reduceTicketCount(getJdbcTemplate(), ticketId, noOfTickets);
21    }
22 
23}
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. Note that 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. Note that the above class extends JdbcDaoSupport and so while creating an instance, the jdbcTemplate object has to be set.

Client Application

Main.java
1package net.javabeat.spring.articles.txn.ticbook.annotation;
2 
3import net.javabeat.spring.articles.txn.BookingService;
4import net.javabeat.spring.articles.txn.Utils;
5 
6import org.springframework.context.ApplicationContext;
7 
8public class Main {
9 
10    public static void main(String[] args) {
11 
12        ApplicationContext context = Utils.getContext("main-annotation.xml");
13 
14        BookingService service = (BookingService)context.getBean("ticketBookingServiceThroughAnnotation");
15        service.bookTicket(111);
16    }
17}
Note that the client application references the configuration file main-annotation.xml which is shown below.
1"1.0" encoding="UTF-8"?>
6xsi:schemaLocation="http://www.springframework.org/schema/beans
7 
8http://www.springframework.org/schema/beans/spring-beans.xsd
9 
10 
11http://www.springframework.org/schema/tx
12 
13 
14http://www.springframework.org/schema/tx/spring-tx.xsd">
15 
16    "transactionManager" />
17 
18    "transactionManager">
19        "dataSource" ref="mySqlDataSource" />
20    
21 
22    "mySqlDataSource" destroy-method="close">
23        "driverClassName" value="com.mysql.jdbc.Driver"/>
24        "url" value="jdbc:mysql://localhost/test"/>
25        "username" value="root"/>
26        "password" value="mother"/>
27    
28 
29    "ticketBookingServiceThroughAnnotation"
30class ="net.javabeat.spring.articles.txn.ticbook.annotation.TicketBookingServiceThroughAnnotation">
31        "dataSource" ref="mySqlDataSource" />
32    
33
Note that for this annotation based approach to work, the element <tx:annotation-driven> has to be specified in the configuration file along with the property transactionManager in which case all the beans that are visible to this context will be considered and those beans which are annotated with @Transactional annotations will be intercepted for transactional processing.
Transaction Management through AOP
We will see the final way of declarative transaction managementprovided by Spring which is AOP based. AOP programming enables the concerns that cross-cut over the application can be separated and can be encapsulated. Since marking the beginning of a transaction, end of a transaction, commiting the database in the case of successful operation and making a rollback for failure operations are really cross-cutting concerns, it is ideal to take AOP based approach for this scenario.
Ticket Booking Service
TicketBookingServiceThroughAop.java
1package net.javabeat.spring.articles.txn.ticbook.aop;
2 
3import net.javabeat.spring.articles.txn.TicketUtils;
4 
5import org.springframework.jdbc.core.support.JdbcDaoSupport;
6 
7public class TicketBookingServiceThroughAop extends JdbcDaoSupport{
8 
9    public void bookTicket(int userId, int ticketId, int noOfTickets){
10 
11        int accountId = TicketUtils.getAccountId(getJdbcTemplate(), userId);
12 
13        float ticketCost = TicketUtils.findTicketCost(getJdbcTemplate(), ticketId);
14        float totalCost = (noOfTickets * ticketCost);
15 
16        TicketUtils.deductMoneyFromAccount(getJdbcTemplate(), accountId, totalCost);
17        TicketUtils.reduceTicketCount(getJdbcTemplate(), ticketId, noOfTickets);
18    }
19}
Note that there is literally no change in Ticket Booking Service class as the AOP related stuffs will be configured in an external configuration file.

Client Application

Main.java
1package net.javabeat.spring.articles.txn.ticbook.aop;
2 
3import net.javabeat.spring.articles.txn.Utils;
4import org.springframework.context.ApplicationContext;
5 
6public class Main {
7    public static void main(String[] args) {
8        ApplicationContext context = Utils.getContext();
9        TicketBookingServiceThroughAop service =
10(TicketBookingServiceThroughAop)context.getBean("ticketBookingServiceThroughAop");
11        service.bookTicket(111);
12    }
13}
The client tries to load the bean ‘ticketBookingServiceThroughAop’ which will actually be a proxy over the real interface TicketBookingService. Have a look at the configuration which is given below.
1<bean id="bookingTransactionInterceptor"class="org.springframework.transaction.interceptor.TransactionInterceptor">
2    <property name="transactionManager" ref="transactionManager" />
3    <property name="transactionAttributes">
4    <props>
5    <prop key="purchase">PROPAGATION_REQUIRED</prop>
6    </props>
7    </property>
8</bean>
9<bean id="ticketBookingProxyService">
10    <property name="target" ref="ticketBookingServiceThroughAop" />
11    <property name="interceptorNames">
12    <list>
13    <value>bookingTransactionInterceptor</value>
14    </list>
15    </property>
16</bean>
17<bean id "ticketBookingServiceThroughAop" class ="net.javabeat.spring.articles.txn.ticbook.aop.TicketBookingServiceThroughAop">
18    <property name="dataSource" ref="mySqlDataSource" />
19</bean>
Note that in the above declaration, we have declared the proxy bean ‘ticketBookingProxyService’ which is an instance of ‘org.springframework.aop.framework.ProxyFactoryBean’. The target for this proxy will be the Ticket Booking Service object which is specified through ‘target’ property. And because we want to intercept the transaction related operations, we have specified the interceptor ‘bookingTransactionInterceptor’ through the element ‘interceptorNames’.

Conclusion

In this article, we have seen how to integrate transaction related operations in Spring framework. We have also discussed the importance of transaction management and we saw how Spring provides the declarative and programmatic way of transaction management through plenty of code samples. Hope the readers attained the basic knowledge of doing transaction management in Springand know how to incorporate it in real-time applications.
If you have any doubts on the spring framework and transaction management, please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about spring frameworkinterview questionsspring and hibernate integration,etc. If you are looking for the detailed knowledge, buy any of the following books for the spring framework.

Comments

comments

No comments: