[jsp]代码库
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import com.sunflower.entity.People;
/**
*
* Spring 使用TransactionTemplate进行事务管理
*
* @author Caihanyuan
* @time 2012-10-7 下午03:50:45
*
*/
public class BankDaoImp implements BankDao {
private JdbcTemplate jdbcTemplate;
private TransactionTemplate transactionTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public TransactionTemplate getTransactionTemplate() {
return transactionTemplate;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
@Override
public double getMoney(final People people) {
double money = people.getMoney();
// 开始事务,如果出现状况则回滚
transactionTemplate.execute(new TransactionCallback<People>() {
@Override
public People doInTransaction(TransactionStatus ts) {
try {
final People people2 = new People();
// 使用JdbcTemplate进行持久化层操作
String sql = "select money from bank where name = ?";
Object[] params = new Object[] { people.getName() };
// 查询
jdbcTemplate.query(sql, params, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs)
throws SQLException {
people2.setMoney(rs.getDouble("money"));
System.out.println(people.getName() + "用户还有"
+ rs.getDouble("money") + "元余款");
System.out.println(people.getName() + "要从账户中取出"
+ people.getMoney() + "元");
if (people2.getMoney() < people.getMoney()) {
System.out.println("余额不足");
people.setMoney(-1);
return;
}
}
});
if (people.getMoney() < 0)
return null;
else {
sql = "update bank set money = ? where name = ?";
Object[] params2 = new Object[] {
people2.getMoney() - people.getMoney(),
people.getName() };
jdbcTemplate.update(sql, params2);
System.out.println("剩余余额:"
+ (people2.getMoney() - people.getMoney()));
}
} catch (Exception e) {
ts.setRollbackOnly();
}
// 如果成功,事务被提交
return people;
}
});
return people.getMoney();
}
}