目录
通过张三给李四转账案例演示事务的控制
applicationContext.xml
jdbc.properties
见上节课
2 项目中准备实体类
package com.msb.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Account implements Serializable {
private Integer id;
private String name;
private Integer money;
}
3 准备DAO层,创建一个根据id修改money的方法
package com.msb.dao;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public interface AccountDao {
int transMoney(int id,int money);
}
package com.msb.dao.impl;
import com.msb.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int transMoney(int id, int money) {
String sql ="update account set money =money +? where id =?";
return jdbcTemplate.update(sql,money,id);
}
}
4 准备Service,创建一个转账的业务方法
package com.msb.service;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public interface AccountService {
int transMoney(int from ,int to,int money);
}
package com.msb.service.impl;
import com.msb.dao.AccountDao;
import com.msb.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public int transMoney(int from, int to, int money) {
int rows=0;
rows+=accountDao.transMoney(from, 0 - money);
rows+=accountDao.transMoney(to, money);
return rows;
}
}
5 测试代码,测试转账
package com.msb.test;
import com.msb.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public class TestTx {
@Test()
public void testTransaction(){
ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = context.getBean(AccountService.class);
int rows = accountService.transMoney(1, 2, 100);
System.out.println(rows);
}
}
版权声明:本文为w1156707958原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。