Java Reference
In-Depth Information
4-6. Managing Transactions Declaratively with the @Transactional
Annotation
Problem
Declaring transactions in the bean configuration file requires knowledge of AOP concepts such as
pointcuts, advices, and advisors. Developers who lack this knowledge might find it hard to enable
declarative transaction management.
Solution
In addition to declaring transactions in the bean configuration file with pointcuts, advices, and advisors,
Spring allows you to declare transactions simply by annotating your transactional methods with
@Transactional and enabling the <tx:annotation-driven> element. However, Java 1.5 or higher is
required to use this approach. Note that although you could apply the annotation to an interface
method, it's not a recommended practice.
How It Works
To define a method as transactional, you can simply annotate it with @Transactional . Note that you
should only annotate public methods due to the proxy-based limitations of Spring AOP.
package com.apress.springenterpriserecipes.bookshop.spring;
...
import org.springframework.transaction.annotation.Transactional;
public class JdbcBookShop extends JdbcDaoSupport implements BookShop {
@Transactional
public void purchase(String isbn, String username) {
int price = getJdbcTemplate().queryForInt(
" SELECT PRICE FROM BOOK WHERE ISBN = ? " ,
new Object[] { isbn });
getJdbcTemplate().update(
" UPDATE BOOK_STOCK SET STOCK = STOCK - 1 " +
" WHERE ISBN = ? " , new Object[] { isbn });
getJdbcTemplate().update(
" UPDATE ACCOUNT SET BALANCE = BALANCE - ? " +
" WHERE USERNAME = ? " ,
new Object[] { price, username });
}
}
 
Search WWH ::




Custom Search