标签:ini ati logs private r.java ext nsa log check
软件152班杨锦宏
spring的事务管理,本文的例子是:比如你需要网购一本书,卖书的那一方有库存量以及书的价格,你有账户余额。回想我们在编程中要实现买书这样的功能,由于你的账户表和书的库存量表肯定不是同一张数据库表,所以必定会有一个先后,要么先将账户余额扣除书的价格,紧接着将书的库存量减一,要么反过来。那么问题来了,假如我们先将你的账户余额减掉,然后发现书的库存不足,这时怎么办呢,这就需要事务了,当我们发现书的库存不足时就要回滚事务,将你的余额返回去。只要配置了事务,发生了异常,就回滚。这就是事务的回滚。注:新人理解,如有错误,望指正,谢谢。
配置文件applicationContext.xml:
配置文件jdbc.propertices:
user=root
password=123
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc\:mysql\:///spring?encoding\=UFT-8
initPoolSize=5
maxPoolSize=20
BookShopDao.java:
package spring.tx;
public interface BookShopDao {
public int findBookPriceByIsbn(String isbn);
public void updataBookStock(String isbn);
public void updataUserAccount(String username,int price);
}
BookShopDaoImp.java:
BookShopService.java:
package spring.tx;
public interface BookShopService {
public void purchase(String username,String isbn);
}
BookShopServiceImpl.java:
Cashier.java:
package spring.tx;
import java.util.List;
public interface Cashier {
public void checkout(String username,List<String> isbns);
}
CashierImpl.java:
定义两个异常类:
测试方法:
package spring.tx.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.tx.BookShopDao;
import spring.tx.BookShopService;
import spring.tx.Cashier;
public class SpringTransactionTest {
private ApplicationContext ctx=null;
private BookShopDao bookShopDao;
private BookShopService bookShopService;
private Cashier cashier;
{
ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
bookShopDao =(BookShopDao) ctx.getBean("bookShopDao");
bookShopService=(BookShopService) ctx.getBean("bookShopService");
cashier =(Cashier) ctx.getBean("cashier");
}
@Test
public void testTransactionPropagation(){
List<String > isbns=new ArrayList<String>();
isbns.add("1001");
isbns.add("1002");
cashier.checkout("aaa", isbns);
}
@Test
public void testBookShopService() {
bookShopService.purchase("aaa", "1001");
}
@Test
public void testupdataBookStock(){
bookShopDao.updataBookStock("1001");
}
@Test
public void testUpdataUserAccount(){
bookShopDao.updataUserAccount("aaa", 200);
}
@Test
public void testBookShopDao(){
int price=bookShopDao.findBookPriceByIsbn("1001");
System.out.println(price);
}
}
标签:ini ati logs private r.java ext nsa log check
原文地址:http://www.cnblogs.com/jinhong/p/7095872.html