Spring基础(十五):Spring事务环境搭建
【摘要】 Spring事务环境搭建简单案例:通过张三给李四转账案例演示事务的控制一、数据库中准备表格二、项目中准备实体类package com.lanson.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;/** *...
Spring事务环境搭建
简单案例:
通过张三给李四转账案例演示事务的控制
一、数据库中准备表格
二、项目中准备实体类
package com.lanson.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Author: Lansonli
* @Description: MircoMessage:Mark_7001
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Account implements Serializable {
private Integer id;
private String name;
private Integer money;
}
三、准备DAO层
创建一个根据id修改money的方法
package com.lanson.dao;
/**
* @Author: Lansonli
* @Description: MircoMessage:Mark_7001
*/
public interface AccountDao {
int transMoney(int id,int money);
}
package com.lanson.dao.impl;
import com.lanson.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* @Author: Lansonli
* @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);
}
}
四、准备Service
创建一个转账的业务方法
package com.lanson.service;
/**
* @Author: Lansonli
* @Description: MircoMessage:Mark_7001
*/
public interface AccountService {
int transMoney(int from ,int to,int money);
}
package com.lanson.service.impl;
import com.lanson.dao.AccountDao;
import com.lanson.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author: Lansonli
* @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;
}
}
五、测试代码
测试转账
package com.lanson.test;
import com.lanson.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: Lansonli
* @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);
}
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)