17_Spring_事务环境搭建
通过张三给李四转账案例演示事务的控制
1 数据库中准备表格
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(){
-
ClassPathXmlApplicationContext("applicationContext.xml");ApplicationContext context =new
-
context.getBean(AccountService.class);AccountService accountService =
-
int rows = accountService.transMoney(1, 2, 100);
-
System.out.println(rows);
-
}
- }
标签:17,int,Spring,public,money,import,com,msb,搭建 From: https://www.cnblogs.com/01way/p/17591289.html