Java Reference
In-Depth Information
How It Works
To illustrate the problems caused by concurrent transactions, let's add two new operations to your book
shop for increasing and checking the book stock.
package com.apress.springenterpriserecipes.bookshop.spring;
public interface BookShop {
...
public void increaseStock(String isbn, int stock);
public int checkStock(String isbn);
}
Then you implement these operations as follows. Note that these two operations should also be
declared as transactional.
package com.apress.springenterpriserecipes.bookshop.spring;
...
import org.springframework.transaction.annotation.Transactional;
public class JdbcBookShop extends JdbcDaoSupport implements BookShop {
...
@Transactional
public void increaseStock(String isbn, int stock) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " - Prepare to increase book stock " );
getJdbcTemplate().update(
" UPDATE BOOK_STOCK SET STOCK = STOCK + ? " +
" WHERE ISBN = ? " ,
new Object[] { stock, isbn });
System.out.println(threadName + " - Book stock increased by " + stock);
sleep(threadName);
System.out.println(threadName + " - Book stock rolled back " );
throw new RuntimeException( " Increased by mistake " );
}
@Transactional
public int checkStock(String isbn) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " - Prepare to check book stock " );
int stock = getJdbcTemplate().queryForInt(
" SELECT STOCK FROM BOOK_STOCK WHERE ISBN = ? " ,
new Object[] { isbn });
Search WWH ::




Custom Search