实验目的:
熟练掌握声明式事务管理。
实验内容:
编写一个模拟银行转账的程序,要求在转账时通过Spring对事务进行控制。
实验要求:
(1) 分别使用基于XML和基于注解的声明式事务管理方式来实现。
(2)提交源代码和运行截图。
首先建立项目如图:
1.com.account.service里的ServiceDao和ServiceDaoImpl
package com.account.service;
//接口
public interface ServiceDao {
public void transfer(String account_id_out,String account_id_in,int balance);
}
package com.account.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service("serviceDao")
//实现接口
public class ServiceDaoImpl implements ServiceDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void transfer(String account_id_out, String account_id_in, int balance) {
String sql = "update accounts set balance=balance-? where account_id=?";
String sql2 = "update accounts set balance=balance+? where account_id=?";
jdbcTemplate.update(sql, balance, account_id_out);
jdbcTemplate.update(sql2, balance, account_id_in);
}
}
2.com.account.controller
package com.account.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.account.service.ServiceDao;
@Controller("accountController")
public class AccountController {
@Autowired
private ServiceDao serviceDao;
public String test() {
String message;
try {
serviceDao.transfer(