当前位置: 首页 > news >正文

SpringIOC整合dbUtil做的增删改查以及转账业务的实现

目录

一、xml方式实现

1.介绍lombok插件

2.功能

3.步骤

3.1 idea安装插件(只做一次)

3.2 添加坐标 

3.3 编写注解

4.核心类

4.1 QueryRunner

4.2 query() 查询

4.3 update() 增删改

5.配置文件applicationContext.xml

6.junit测试

6.1使用步骤

6.1.1 坐标

6.1.2 注解(修饰方法)

二、annotation注解方式实现

1.控制层(cotroller)

2.业务层(service)

3.数据访问层(dao)

4.配置文件applicationContext.xml

三、configuration配置类方式实现

1.ApplicationConfig

2.DataConfig 替换applicationContext.xml

3.测试类

四、在xml基础上实现转账业务

1.同一个业务方法的多个dao方法公用一个connection对象

2.ThreadLocal

3.通过连接对象进行事务的统一管理

5.项目总结:


一、xml方式实现

1.介绍lombok插件

dbUtil-阿帕奇提供操作数据库的插件

2.功能

对实体类自动,动态生成getset,无参有参 toString.....

3.步骤
3.1 idea安装插件(只做一次)

3.2 添加坐标 
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
3.3 编写注解
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Account implements Serializable {private int aid;private String aname;private int amoney;public Account(String aname, int amoney) {this.aname = aname;this.amoney = amoney;}
}
4.核心类
4.1 QueryRunner
//操作数据库的核心类QueryRunner queryRunner;public void setQueryRunner(QueryRunner queryRunner) {this.queryRunner = queryRunner;}
4.2 query() 查询
@Overridepublic void save(Account account) {try {queryRunner.update("insert into account(aname,amoney) value(?,?)",account.getAname(),account.getAmoney());} catch (SQLException throwables) {throwables.printStackTrace();}}
@Override
public void updateById(Account account) {try {queryRunner.update("udpate account set aname=?,amoney=? where aid=?",account.getAname(),account.getAmoney(),account.getAid());} catch (SQLException throwables) {throwables.printStackTrace();}
}@Override
public void deleteById(int id) {try {queryRunner.update("delete from account where aid=?",id);} catch (SQLException throwables) {throwables.printStackTrace();}
}
4.3 update() 增删改
@Override
public Account findByName(String name) {try {return queryRunner.query("select * from account where aname=?",new BeanHandler<Account>(Account.class),name);} catch (SQLException throwables) {throwables.printStackTrace();}return null;
}@Override
public List<Account> findAll() {try {return queryRunner.query("select * from account",new BeanListHandler<Account>(Account.class));} catch (SQLException throwables) {throwables.printStackTrace();}return null;
}
5.配置文件applicationContext.xml
<!--加载资源文件--><context:property-placeholder location="jdbc.properties"></context:property-placeholder><!--注入数据源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${msg1}"></property><property name="jdbcUrl" value="${msg2}"></property><property name="user" value="${msg3}"></property><property name="password" value="${msg4}"></property></bean><!--注入QueryRunner--><bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"><constructor-arg name="ds" ref="dataSource"></constructor-arg></bean><!--注入dao--><bean id="mapperImp" class="com.ztt.dao.AccountMapperImp"><property name="queryRunner" ref="queryRunner"></property></bean><!--注入service--><bean id="service" class="com.ztt.service.AccountServiceImp"><property name="mapper" ref="mapperImp"></property></bean><!--注入controller--><bean id="controller" class="com.ztt.controller.AccountControllerImp"><property name="service" ref="service"></property></bean>
6.junit测试
6.1使用步骤
6.1.1 坐标
<!--单元测试-->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope>
</dependency>
<!--数据源--><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version>
</dependency>
6.1.2 注解(修饰方法)

@Test======>可以运行的方法

@Before====>@Test运行之前

@After=====>@Test运行之后

方式一:
public class Test01 {ClassPathXmlApplicationContext applicationContext =null;IAccountController controller = null;@Beforepublic void beforeMethod(){applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");controller = (IAccountController) applicationContext.getBean("controller");}@Afterpublic void afterMethod(){applicationContext.close();}@Testpublic void show1(){controller.save(new Account("张甜甜",2000));controller.save(new Account("许娜",2000));}@Testpublic void show2(){List<Account> all = controller.findAll();for (int i = 0; i < all.size(); i++) {Account account =  all.get(i);System.out.println(account);}}}
方式二:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test02 {@AutowiredIAccountController controller;@Testpublic void show1(){controller.save(new Account("张甜甜",2000));controller.save(new Account("许娜",2000));}@Testpublic void show2(){List<Account> all = controller.findAll();for (int i = 0; i < all.size(); i++) {Account account =  all.get(i);System.out.println(account);}}@Testpublic void show3(){controller.transfer("张甜甜","许娜",100);}
}

二、annotation注解方式实现

1.控制层(cotroller)
@Controller("controller")
public class AccountControllerImp implements IAccountController {@AutowiredIAccountService service;
2.业务层(service)
@Service
public class AccountServiceImp implements IAccountService{@AutowiredIAccountMapper mapper;
3.数据访问层(dao)
@Repository
public class AccountMapperImp implements IAccountMapper{//操作数据库的核心类@AutowiredQueryRunner queryRunner;
4.配置文件applicationContext.xml
<!--加载资源文件--><context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder><!--注入数据源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${msg1}"></property><property name="jdbcUrl" value="${msg2}"></property><property name="user" value="${msg3}"></property><property name="password" value="${msg4}"></property></bean><!--注入QueryRunner--><bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"><constructor-arg name="ds" ref="dataSource"></constructor-arg></bean><!--扫描--><context:component-scan base-package="com.ztt"></context:component-scan>

测试类同上

三、configuration配置类方式实现

在三层框架的基础上新建一个包config,用来写配置类

1.ApplicationConfig
@Configuration
@ComponentScan(basePackages = "com.ztt")
@Import(DataConfig.class)
public class ApplicationConfig {
}
2.DataConfig 替换applicationContext.xml
@Configuration
@PropertySource(value = "classpath:jdbc.properties")
public class DataConfig {@Value("${msg1}")private String driverClass;@Value("${msg2}")private String jdbcUrl;@Value("${msg3}")private String user;@Value("${msg4}")private String password;//    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
//        <property name="driverClass" value="${msg1}"></property>
//        <property name="jdbcUrl" value="${msg2}"></property>
//        <property name="user" value="${msg3}"></property>
//        <property name="password" value="${msg4}"></property>
//    </bean>@Beanpublic DataSource dataSource(){try {ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();comboPooledDataSource.setDriverClass(driverClass);comboPooledDataSource.setJdbcUrl(jdbcUrl);comboPooledDataSource.setUser(user);comboPooledDataSource.setPassword(password);return comboPooledDataSource;} catch (PropertyVetoException e) {e.printStackTrace();}return null;}//    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
//        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
//    </bean>@Beanpublic QueryRunner queryRunner(){return new QueryRunner(dataSource());}}
3.测试类

 

四、在xml基础上实现转账业务

目的:业务层进行事务管理

1.同一个业务方法的多个dao方法公用一个connection对象
2.ThreadLocal
3.通过连接对象进行事务的统一管理

ConnectionUtil连接工具类:

public class ConnectionUtil {//装配数据源DataSource dataSource;public void setDataSource(DataSource dataSource) {this.dataSource = dataSource;}//线程区域对象ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>();//获取连接public Connection createCon(){Connection connection = null;try {//1.获取线程内的连接对象connection=threadLocal.get();//2.判断if(connection==null){connection=dataSource.getConnection();//创建连接threadLocal.set(connection);//保存}return connection;} catch (SQLException throwables) {throwables.printStackTrace();}return connection;}//移除连接public void removeCon(){threadLocal.remove();//移除连接}}

TransactionUtil事务管理工具类:

public class TransactionUtil {//注入连接工具类ConnectionUtil connectionUtil;public void setConnectionUtil(ConnectionUtil connectionUtil) {this.connectionUtil = connectionUtil;}//开启事务public void beginTx(){try {connectionUtil.createCon().setAutoCommit(false);} catch (SQLException throwables) {throwables.printStackTrace();}}//提交事务public void commitTx(){try {connectionUtil.createCon().commit();} catch (SQLException throwables) {throwables.printStackTrace();}}//回滚事务public void rollbackTx(){try {connectionUtil.createCon().rollback();} catch (SQLException throwables) {throwables.printStackTrace();}}//关闭事务public void closeTx(){try {connectionUtil.createCon().close();//关闭事务connectionUtil.removeCon();//移除事务} catch (SQLException throwables) {throwables.printStackTrace();}}
}

AccountMapperImp:

public class AccountMapperImp implements IAccountMapper{//操作数据库的核心类QueryRunner queryRunner;public void setQueryRunner(QueryRunner queryRunner) {this.queryRunner = queryRunner;}//注入连接工具ConnectionUtil connectionUtil;public void setConnectionUtil(ConnectionUtil connectionUtil) {this.connectionUtil = connectionUtil;}

AccountServiceImp:

public class AccountServiceImp implements IAccountService{IAccountMapper mapper;public void setMapper(IAccountMapper mapper) {this.mapper = mapper;}//装配TransactionUtil transactionUtil;public void setTransactionUtil(TransactionUtil transactionUtil) {this.transactionUtil = transactionUtil;}@Overridepublic void transfer(String sourceName, String targetName, int money) {try {transactionUtil.beginTx();//1.查询数据Account sourceAccount = mapper.findByName(sourceName);Account targetAccount = mapper.findByName(sourceName);//2.转账sourceAccount.setAmoney(sourceAccount.getAmoney()-money);targetAccount.setAmoney(targetAccount.getAmoney()+money);//3.修改数据库mapper.updateById(sourceAccount);int a=10/0;//模拟异常mapper.updateById(targetAccount);transactionUtil.commitTx();} catch (Exception e) {e.printStackTrace();transactionUtil.rollbackTx();} finally {transactionUtil.closeTx();}}

 AccountControllerImp:

public class AccountControllerImp implements IAccountController {IAccountService service;public void setService(IAccountService service) {this.service = service;}@Overridepublic void transfer(String sourceName, String targetName, int money) {service.transfer(sourceName,targetName,money);}public void save(Account account) {service.save(account);}

配置文件applicationContext.xml

        在原有的基础上注入连接工具类、事务工具类、以及在业务层注入事务管理工具类

<!--连接工具类-->
<bean id="connectionUtil" class="com.ztt.util.ConnectionUtil">
<property name="dataSource" ref="dataSource"></property>
</bean><!--事务工具类-->
<bean id="transactionUtil" class="com.ztt.util.TransactionUtil">
<property name="connectionUtil" ref="connectionUtil"></property>
</bean><!--注入dao-->
<bean id="mapperImp" class="com.ztt.dao.AccountMapperImp">
<property name="queryRunner" ref="queryRunner"></property>
</bean><!--注入service-->
<bean id="service" class="com.ztt.service.AccountServiceImp">
<property name="mapper" ref="mapperImp"></property>
<property name="transactionUtil" ref="transactionUtil"></property>
</bean><!--注入controller-->
<bean id="controller" class="com.ztt.controller.AccountControllerImp">
<property name="service" ref="service"></property>
</bean>

测试方法:

@Testpublic void show3(){controller.transfer("张甜甜","许娜",100);}
5.项目总结:

1.事务管理应该由service层进行实现

代码优化:

目的:业务层进行事务管理

1.同一个业务方法的多个dao方法公用一个connection对象

2.ThreadLocal

3.通过连接对象进行事务的统一管理

相关文章:

SpringIOC整合dbUtil做的增删改查以及转账业务的实现

目录 一、xml方式实现 1.介绍lombok插件 2.功能 3.步骤 3.1 idea安装插件(只做一次) 3.2 添加坐标 3.3 编写注解 4.核心类 4.1 QueryRunner 4.2 query() 查询 4.3 update() 增删改 5.配置文件applicationContext.xml 6.junit测试 6.1使用步骤 6.1.1 坐标 6.1.2…...

【Nacos无压力源码领读】(二) 集成 LoadBanlancer 与 OpenFeign

上一篇文章中, 详细介绍了 Nacos 注册中心的原理, 相信看完后, 大家应该完全掌握了 Nacos 客户端是如何自动进行服务注册的, 以及 Nacos 客户端是如何订阅服务实例信息的, 以及 Nacos 服务器是如何处理客户端的注册和订阅请求的; 本文承上启下, 在订阅服务实例的基础上, 介绍如…...

CP AUTOSAR标准之DefaultErrorTracer(AUTOSAR_SWS_DefaultErrorTracer)(更新中……)

1 简介和功能概述 本规范描述了默认错误跟踪器的API。基础软件中检测到的所有开发和运行时错误都会报告给此模块。API参数允许跟踪错误来源和类型: 检测到错误的模块检测到错误的函数错误类型此模块API背后的功能不在本规范的范围内。软件开发人员和软件集成商应根据其特定应用…...

SpringMVC (发送请求——>参数传递—— >响应数据)

设置请求访问路径 RequestMapper&#xff1a;将请求访问路径和我们业务层的方法联系起来 ResponseBody&#xff1a;将我们业务层方法的返回值转化为json&#xff0c;xml或其他格式的数据返回给页面 两种请求 get请求 post请求 测试案例 RequestMapping("/getNameAndAge&…...

认识Modbus RTU与Modbus TCP

&#xff08;选自成都纵横智控-Modbus RTU与Modbus TCP协议区别详解 &#xff09; Modbus RTU 和 Modbus TCP 是两种常用的工业通信协议&#xff0c;用于连接电子设备&#xff0c;但它们在多方面有所不同。以下是它们的详细比较&#xff1a; Modbus RTU 协议类型&#xff1a; …...

如何在 Kubernetes 中使用 ClickHouse 和 JuiceFS

ClickHouse 结合 JuiceFS 一直是一个热门的组合&#xff0c;社区中有多篇实践案例。今天的文章来自美国公司 Altinity&#xff0c;一家提供 ClickHouse 商业服务的企业&#xff0c;作者是 Vitaliy Zakaznikov&#xff0c;他尝试了这个组合并公开了过程中使用的代码。原文有两篇…...

云计算任务调度优化matlab仿真,对比蚁群优化和蛙跳优化

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.本算法原理 4.1 ACO蚁群优化 4.2 蛙跳优化 5.完整程序 1.程序功能描述 云计算任务调度优化,优化目标位任务消耗时间&#xff0c;调度后的经济效益以及设备功耗&#xff0c;对比蚁群优化算法和蛙跳优化…...

基于双PI+EKF扩展卡尔曼滤波的PMSM速度控制simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 4.1 PMSM数学模型 4.2 双PI控制器设计 4.3 扩展卡尔曼滤波器(EKF) 4.4 控制系统实现 5.完整工程文件 1.课题概述 基于双PIEKF扩展卡尔曼滤波的PMSM速度控制simulink建模与仿真。对比基于双PI的扩展卡…...

医疗器械注册资源宝库数屿医械官方平台!

医学影像设备市场作为医疗器械领域的佼佼者&#xff0c;技术门槛高且规模庞大&#xff0c;2021年全球规模达458亿美元&#xff0c;预计2022年逼近500亿美元&#xff0c;增长动力源自技术革新与临床需求攀升。中国市场亦不甘落后&#xff0c;受政策驱动与市场需求双重提振&#…...

Django如何移除数据库字段?

关键步骤&#xff1a; 第一步&#xff1a;python manage.py makemigrations 你的项目名称第二步&#xff1a; python manage.py migrate (.venv) PS D:\python_workpace\django_xitong_shezhi\pythonProject\myproject> python manage.py makemigrations myproject Migra…...

阶段项目——拼图小游戏

Java学习笔记&#xff08;新手纯小白向&#xff09; 第一章 JAVA基础概念 第二章 JAVA安装和环境配置 第三章 IntelliJ IDEA安装 第四章 运算符 第五章 运算符联系 第六章 判断与循环 第七章 判断与循环练习 第八章 循环高级综合 第九章 数组介绍及其内存图 第十章 数…...

基于本地消息表实现分布式事务(最终一致性)

前言 传统单体架构下&#xff0c;所有的功能模块都在一个应用下&#xff0c;所有的代码和业务逻辑都在同一个应用下实现&#xff0c;所以保证数据的一致性就很简单&#xff0c;保证相关操作都在同一个本地事务下就可以了。 但是在微服务架构下&#xff0c;将一个应用拆分成了…...

大数据mapper书写范式hdfs

文章目录 1. 大数据mapper书写范式hdfs 1. 大数据mapper书写范式hdfs import json import sysdef read_input(input_stream):for line in input_stream:yield line.rstrip(\n)def load_json_data(json_line):try:data json.loads(json_line)unique_id data.get(id)combined_…...

ubuntu将软件放到任务栏

右键点击这个 pycharm 方法1&#xff1a; 方法2&#xff1a; sudo nano /usr/share/applications/PyCharm.desktop 编辑这个 [Desktop Entry] NamePyCharm CommentPyCharm Integrated Development Environment Exec/path/to/PyCharm.sh Icon/path/to/PyCharm.svg Terminalf…...

Spring Boot 参数校验 Validation 使用

概述 当我们想提供可靠的 API 接口&#xff0c;对参数的校验&#xff0c;以保证最终数据入库的正确性&#xff0c;是必不可少的活。前、后端校验都是保证参数的准确性的手段之一&#xff0c;前端校验并不安全&#xff0c;任何人都可以通过接口来调用我们的服务&#xff0c;就算…...

基于el-table的表格点选和框选功能

开篇 本篇文章旨在实现一个基于el-table的表格点选和框选功能&#xff0c;除此之外&#xff0c;还支持多种模式的切换、自定义勾选日期等。且&#xff0c;该表格后续可能还会持续优化&#xff01; 功能介绍 表格点选和框选功能&#xff08;没有点击ctrl键的情况下&#xff09;…...

LabVIEW压电陶瓷阻抗测试系统

开发了一种基于LabVIEW软件与PXI模块化仪器的压电陶瓷阻抗测试系统。该系统能在高电压工作条件下测量压电陶瓷的阻抗特性&#xff0c;包括阻抗模值与阻抗角的频率特性&#xff0c;为压电陶瓷的进一步分析与应用提供了重要参考。 项目背景 现有的阻抗测试仪大多只能在低电压条件…...

电销机器人能大幅度提升效率

1、安全稳定性能好 营销机器人的稳定性非常强&#xff0c;在使用性能方面会有更好的优势&#xff0c;而且用的过程中也可以不断的这些模块更新和功能升级&#xff0c;所以会不断的满足大家更多的使用要求&#xff0c;在操作使用的时候非常简单和方便&#xff0c;直接就可以给客…...

虚拟机能访问网页但ping不通百度

最近遇到了奇怪的问题&#xff0c;虚拟机能访问网页&#xff0c;但ping不通百度&#xff0c;记录一下问题的排查过程。 能访问网页&#xff0c;说明DNS、TCP和HTTP没有问题&#xff0c;ping不通&#xff0c;说明ICMP应该出了问题。 首先通过traceroute追踪报文的转发过程&…...

RK3588开发笔记-buildroot编译配置

目录 前言 一、buildroot简介 二、buildroot配置编译 buildroot config配置 buildroot 编译 buildroot 如何单独编译某个软件包 何时需要完全重建 如何完全重建 总结 前言 Rockchip RK3588 是一款强大的多核处理器,广泛应用于边缘计算、人工智能、嵌入式系统等领域。为了在…...

Vim 调用外部命令学习笔记

Vim 外部命令集成完全指南 文章目录 Vim 外部命令集成完全指南核心概念理解命令语法解析语法对比 常用外部命令详解文本排序与去重文本筛选与搜索高级 grep 搜索技巧文本替换与编辑字符处理高级文本处理编程语言处理其他实用命令 范围操作示例指定行范围处理复合命令示例 实用技…...

vscode里如何用git

打开vs终端执行如下&#xff1a; 1 初始化 Git 仓库&#xff08;如果尚未初始化&#xff09; git init 2 添加文件到 Git 仓库 git add . 3 使用 git commit 命令来提交你的更改。确保在提交时加上一个有用的消息。 git commit -m "备注信息" 4 …...

云计算——弹性云计算器(ECS)

弹性云服务器&#xff1a;ECS 概述 云计算重构了ICT系统&#xff0c;云计算平台厂商推出使得厂家能够主要关注应用管理而非平台管理的云平台&#xff0c;包含如下主要概念。 ECS&#xff08;Elastic Cloud Server&#xff09;&#xff1a;即弹性云服务器&#xff0c;是云计算…...

Leetcode 3576. Transform Array to All Equal Elements

Leetcode 3576. Transform Array to All Equal Elements 1. 解题思路2. 代码实现 题目链接&#xff1a;3576. Transform Array to All Equal Elements 1. 解题思路 这一题思路上就是分别考察一下是否能将其转化为全1或者全-1数组即可。 至于每一种情况是否可以达到&#xf…...

工业安全零事故的智能守护者:一体化AI智能安防平台

前言&#xff1a; 通过AI视觉技术&#xff0c;为船厂提供全面的安全监控解决方案&#xff0c;涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面&#xff0c;能够实现对应负责人反馈机制&#xff0c;并最终实现数据的统计报表。提升船厂…...

《Qt C++ 与 OpenCV:解锁视频播放程序设计的奥秘》

引言:探索视频播放程序设计之旅 在当今数字化时代,多媒体应用已渗透到我们生活的方方面面,从日常的视频娱乐到专业的视频监控、视频会议系统,视频播放程序作为多媒体应用的核心组成部分,扮演着至关重要的角色。无论是在个人电脑、移动设备还是智能电视等平台上,用户都期望…...

基于当前项目通过npm包形式暴露公共组件

1.package.sjon文件配置 其中xh-flowable就是暴露出去的npm包名 2.创建tpyes文件夹&#xff0c;并新增内容 3.创建package文件夹...

微信小程序 - 手机震动

一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注&#xff1a;文档 https://developers.weixin.qq…...

基础测试工具使用经验

背景 vtune&#xff0c;perf, nsight system等基础测试工具&#xff0c;都是用过的&#xff0c;但是没有记录&#xff0c;都逐渐忘了。所以写这篇博客总结记录一下&#xff0c;只要以后发现新的用法&#xff0c;就记得来编辑补充一下 perf 比较基础的用法&#xff1a; 先改这…...

(二)原型模式

原型的功能是将一个已经存在的对象作为源目标,其余对象都是通过这个源目标创建。发挥复制的作用就是原型模式的核心思想。 一、源型模式的定义 原型模式是指第二次创建对象可以通过复制已经存在的原型对象来实现,忽略对象创建过程中的其它细节。 📌 核心特点: 避免重复初…...