Spring整合MyBatis小实例(转账功能)

实现步骤

一,引入依赖

<!--仓库--><repositories><!--spring里程碑版本的仓库--><repository><id>repository.spring.milestone</id><name>Spring Milestone Repository</name><url>https://repo.spring.io/milestone</url></repository></repositories><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.0-M2</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>6.0.0-M2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.8</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.11</version></dependency><!--        这里版本不能随意选,选2.0.7这个不会出问题--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.7</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.13</version></dependency><!--        spring对Junit的支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>6.0.0-M2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency>
<!--        使用Resource需要的依赖--><dependency><groupId>jakarta.annotation</groupId><artifactId>jakarta.annotation-api</artifactId><version>2.1.1</version></dependency></dependencies>

二,基于三层架构,准备所有的包和类

bean层(Account类)

package com.hkd.spring6.bean;public class Account {private String actno;private Double balance;public Account() {}public Account(String actno, Double balance) {this.actno = actno;this.balance = balance;}public String getActno() {return actno;}public void setActno(String actno) {this.actno = actno;}public Double getBalance() {return balance;}public void setBalance(Double balance) {this.balance = balance;}@Overridepublic String toString() {return "Account{" +"actno='" + actno + '\'' +", balance=" + balance +'}';}
}

service层

接口
package com.hkd.spring6.service;public interface ActService {void transfer(String fromAct, String toAct, double money);
}
实现类
package com.hkd.spring6.service.impl;import com.hkd.spring6.bean.Account;
import com.hkd.spring6.mapper.ActMapper;
import com.hkd.spring6.service.ActService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;@Service("actService")
@Transactional
public class ActServiceImpl implements ActService {//    @Autowired
//    private ActMapper actMapper;//    MyBatis为mapper接口自动生成的实现类类名是mapper类首字母小写@Resource(name = "actMapper")private ActMapper actMapper;@Overridepublic void transfer(String fromAct, String toAct, double money) {Account select1 = actMapper.select(fromAct);if (select1.getBalance() < money) {throw new RuntimeException("余额不足");}Account select2 = actMapper.select(toAct);select1.setBalance(select1.getBalance() -money);select2.setBalance(select2.getBalance() + money);int update = actMapper.update(select1);update += actMapper.update(select2);if (update != 2) {throw new RuntimeException("转账失败");}}
}

mapper层

接口
package com.hkd.spring6.mapper;import com.hkd.spring6.bean.Account;public interface ActMapper {Account select(String actno);int update(Account account);
}
sql映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.hkd.spring6.mapper.ActMapper"><select id="select" resultType="Account">select * from t_bank where actno = #{actno}</select><update id="update">update t_bank set balance = #{balance} where actno = #{actno}</update>
</mapper>

三,配置文件的完成

1.jdbc.properties(数据库相关配置文件)

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis
jdbc.user = root
jdbc.password = hsp

2.MyBatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings>
<!--        开启日志打印--><setting name="logImpl" value="STDOUT_LOGGING"/></settings>
</configuration>

3.Spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><context:component-scan base-package="com.hkd.spring6"/><context:property-placeholder location="jdbc.properties"/><bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.user}"/><property name="password" value="${jdbc.password}"/></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="datasource"/></bean><tx:annotation-driven transaction-manager="transactionManager"/><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="datasource"/></bean><bean class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="datasource"/><property name="typeAliasesPackage" value="com.hkd.spring6.bean"/><property name="configLocation" value="mybatis-config.xml"/></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.hkd.spring6.mapper"/></bean></beans>

四,测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class TestSm {@Autowiredprivate ActService actService;@Testpublic void testSm(){try {actService.transfer("act-001","act-002",1);System.out.println("转账成功");} catch (Exception e){System.out.println("转账失败");e.printStackTrace();}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/26073.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【VB6|第22期】用SQL的方式读取Excel数据

日期&#xff1a;2023年8月7日 作者&#xff1a;Commas 签名&#xff1a;(ง •_•)ง 积跬步以致千里,积小流以成江海…… 注释&#xff1a;如果您觉得有所帮助&#xff0c;帮忙点个赞&#xff0c;也可以关注我&#xff0c;我们一起成长&#xff1b;如果有不对的地方&#xff…

系统架构设计高级技能 · 系统质量属性与架构评估(二)【系统架构设计师】

系列文章目录 系统架构设计高级技能 软件架构概念、架构风格、ABSD、架构复用、DSSA&#xff08;一&#xff09;【系统架构设计师】 系统架构设计高级技能 系统质量属性与架构评估&#xff08;二&#xff09;【系统架构设计师】 系统架构设计高级技能 软件可靠性分析与设计…

钉钉微应用

钉钉微应用 在做钉钉微应用开发的时候&#xff0c;遇到了一些相关性的问题&#xff0c;特此记录下&#xff0c;有遇到其他问题的&#xff0c;欢迎一起讨论 调试工具 当我们基于钉钉开发微应用时&#xff0c;难免会遇到调用钉钉api后的调试&#xff0c;这个时候可以安装eruda…

HTML,url,unicode编码

目录标题 HTML实体编码urlcode编码unicode编码小结基础例题高级例题 HTML实体编码 实体表示&#xff1a; 以&符号开始&#xff0c;后面跟着一个预定义的实体的名称&#xff0c;或是一个#符号以及字符的十进制数字。 例&#xff1a; <p>hello</p> <!-- 等同…

基于LNMP架构搭建Discuz论坛

LNMP: L---->linux系统&#xff0c;操作系统。 N----->nginx网站服务&#xff08;前端),提供前端的静态页面服务。同时具有代理、转发的作用。&#xff08;转发就是转发后端请求&#xff0c;转发PHP&#xff09;&#xff0c;nginx没有处理动态资源的功能&#xff0c;他有…

怎样将项目jar包放到服务器上

目录 1、在配置文件中配置账号密码 2.在父级的pom里面&#xff0c;加上这个标签 3. deploy部署 4. 注&#xff1a;这两个id得匹配上&#xff08;原因&#xff1a;有的人会只有上传到测试包的权限&#xff0c;id对应&#xff0c;拥有账号密码的才能有权限&#xff09; 5.子项…

RocketMQ基本概念和高级原理

基础概念 消息模型 RocketMQ 主要由 Producer、Broker、Consumer 三部分组成&#xff0c;其中 Producer 负责生产消息&#xff0c;Consumer 负责消费消息&#xff0c;Broker 负责存储消息。Broker 在实际部署过程中对应一台服务器&#xff0c;每个 Broker 可以存储多个 Topic…

谷粒商城第十天-获取分类属性分组(前端组件抽取父子组件交互)

目录 一、总述 1.1 前端思路 1.2 后端思路 二、前端部分 2.1 将分类树前端代码抽取成一个组件 2.2 使用elementUI的组件实现左右组件功能 2.3 使用事件机制进行组件通信 三、后端部分 四、总结 一、总述 说一下今天需要实现一个什么样子的功能&#xff1a; 很简单&am…

Rpc异步日志模块

Rpc异步日志模块作用 在一个大型分布式系统中&#xff0c;任何部署的分布式节点都可能发生崩溃&#xff0c;试想如果用普通的办法&#xff0c;即先排查哪个节点down掉了&#xff0c;找到down掉的节点后采取调试工具gdb调试该节点&#xff0c;进而排查宕机的原因。这中排查方法…

【LeetCode】地下城游戏(动态规划)

地下城游戏 题目描述算法分析编程代码 链接: 地下城游戏 题目描述 算法分析 编程代码 class Solution { public:int calculateMinimumHP(vector<vector<int>>& dungeon) {int m dungeon.size();int n dungeon[0].size();vector<vector<int>> d…

linux c++网络编程基础:服务端与客户端的实现

在Linux环境下,我们可以使用socket编程来实现网络通信。下面是一个简单的C++版本的客户端和服务端的示例代码。 服务端代码: #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <string.h> #

BigDecimal的用法及遇到的问题

1.Non-terminating decimal expansion; no exact representable decimal result. 原因是使用除法未指定保留的小数位数&#xff0c;当除不尽的时候会报这个错误&#xff0c;解决方法&#xff1a; BigDecimal avgCasePrice totalPrice.divide(BigDecimal.valueOf(2),new Math…

【flink】Chunk splitting has encountered exception

执行任务报错&#xff1a; Chunk splitting has encountered exception 错误信息截图&#xff1a; 完整的错误信息&#xff1a; 16:30:43,911 ERROR org.apache.flink.runtime.source.coordinator.SourceCoordinator [SourceCoordinator-Source: CDC Sourceorg.jobslink.flink…

百度智能创做AI平台

家人们好&#xff0c;在数字化时代&#xff0c;人工智能正引领着一场前所未有的创新浪潮。今天&#xff0c;我们将为大家介绍百度智能创做AI平台&#xff0c;这个为创意赋能、助力创作者的强大工具。无论你是创意工作者、内容创作者&#xff0c;还是想要释放内心创造力的个人&a…

Django------信号

Django 框架包含了一个信号机制&#xff0c;它允许若干个发送者&#xff08;sender&#xff09;通知一组接收者&#xff08;receiver&#xff09;某些特定操作或事件(events)已经发生了&#xff0c; 接收者收到指令信号(signals)后再去执行特定的操作。本文主要讲解Django信号(…

electron-builder 打包 exe 报错 Error output: Plugin not found, cannot call UAC::_

报错信息&#xff1a; Error: C:\Users\***\AppData\Local\electron-builder\cache\nsis\nsis-3.0.1.13\Bin\makensis.exe exited with code 1 Output: Command line defined: "APP_IDcom.baidu.app" Command line defined: "APP_GUIDfb00ccb0-0875-5f26-8d91-…

03 |「用户导航」

前言 实践是最好的学习方式&#xff0c;技术也如此。 文章目录 前言 1、向左箭头 需求&#xff1a;向应用红栏添加向上按钮&#xff08;向左箭头&#xff09; 向左箭头始终用于导航到层次结构中的父屏幕&#xff1b; 与后退按钮的区别是&#xff0c;后退按钮导航至用户上次查看…

Redis 单线程VS多线程

面试题 redis到底是单线程还是多线程&#xff1f;IO多路复用是什么&#xff1f;redis为什么快&#xff1f; Redis单线程 是什么 Redis的版本很多3.x、4.x、6.x&#xff0c;版本不同架构也是不同的&#xff0c;不限定版本问是否单线程也不太严谨。 1、版本3.x &#xff0c;最…

面试测试开发被问到数据库索引不知道怎么办?

提出的问题 什么情况下创建索引&#xff0c;什么时候不需要索引&#xff1f; 索引的种类有哪些&#xff1f; 什么是索引 索引就是帮助数据库管理系统高效获取数据的数据结构&#xff0c;就好比一本书的目录&#xff0c;它可以帮我们快速进行特定值的定位与查找&#xff0c;…

最新AI创作系统ChatGPT源码V2.5.8/支持GPT4.0+GPT联网提问/支持ai绘画Midjourney+Prompt+MJ以图生图+思维导图生成!

使用Nestjs和Vue3框架技术&#xff0c;持续集成AI能力到系统&#xff01; 最新版【V2.5.8】更新&#xff1a; 新增 MJ 官方图片重新生成指令功能同步官方 Vary 指令 单张图片对比加强 Vary(Strong) | Vary(Subtle)同步官方 Zoom 指令 单张图片无限缩放 Zoom out 2x | Zoom ou…