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

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();}}
}

相关文章:

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

实现步骤 一&#xff0c;引入依赖 <!--仓库--><repositories><!--spring里程碑版本的仓库--><repository><id>repository.spring.milestone</id><name>Spring Milestone Repository</name><url>https://repo.spring.i…...

List集合的对象传输的两种方式

说明&#xff1a;在一些特定的情况&#xff0c;我们需要把对象中的List集合属性存入到数据库中&#xff0c;之后把该字段取出来转为List集合的对象使用&#xff08;如下图&#xff09; 自定义对象 public class User implements Serializable {/*** ID*/private Integer id;/*…...

海外媒体发稿:软文写作方法方式?一篇好的软文理应合理规划?

不同种类的软文会有不同的方式&#xff0c;下面小编就来来给大家分析一下&#xff1a; 方法一、要选定文章的突破点&#xff1a; 所说突破点就是这篇文章文章软文理应以什么样的视角、什么样的见解、什么样的语言设计理念、如何文章文章的标题来写。不同种类的传播效果&#…...

【秋招】算法岗的八股文之机器学习

目录 机器学习特征工程常见的计算模型总览线性回归模型与逻辑回归模型线性回归模型逻辑回归模型区别 朴素贝叶斯分类器模型 (Naive Bayes)决策树模型随机森林模型支持向量机模型 (Support Vector Machine)K近邻模型神经网络模型卷积神经网络&#xff08;CNN&#xff09;循环神经…...

为什么list.sort()比Stream().sorted()更快?

真的更好吗&#xff1f; 先简单写个demo List<Integer> userList new ArrayList<>();Random rand new Random();for (int i 0; i < 10000 ; i) {userList.add(rand.nextInt(1000));}List<Integer> userList2 new ArrayList<>();userList2.add…...

SQL账户SA登录失败,提示错误:18456

错误代码 18456 表示 SQL Server 登录失败。这个错误通常表示提供的凭据&#xff08;用户名和密码&#xff09;无法成功验证或者没有权限访问所请求的数据库。以下是一些常见的可能原因和解决方法&#xff1a; 1.错误的凭据&#xff1a;请确认提供的SA账户的用户名和密码是否正…...

Linux 终端操作命令(1)

Linux 命令 终端命令格式 command [-options] [parameter] 说明&#xff1a; command&#xff1a;命令名&#xff0c;相应功能的英文单词或单词的缩写[-options]&#xff1a;选项&#xff0c;可用来对命令进行控制&#xff0c;也可以省略parameter&#xff1a;传给命令的参…...

java与javaw运行jar程序

运行jar程序 一、java.exe启动jar程序 (会显示console黑窗口) 1、一般用法&#xff1a; java -jar myJar.jar2、重命名进程名称启动&#xff1a; echo off copy "%JAVA_HOME%\bin\java.exe" "%JAVA_HOME%\bin\myProcess.exe" myProcess -jar myJar.jar e…...

安装和配置 Home Assistant 教程 HACS Homkit 米家等智能设备接入

安装和配置 Home Assistant 教程 简介 Home Assistant 是一款开源的智能家居自动化平台&#xff0c;可以帮助你集成和控制各种智能设备&#xff0c;从灯光到温度调节器&#xff0c;从摄像头到媒体播放器。本教程将引导你如何在 Docker 环境中安装和配置 Home Assistant&#…...

解决 Android Studio 的 Gradle 面板上只有关于测试的 task 的问题

文章目录 问题描述解决办法 笔者出问题时的运行环境&#xff1a; Android Studio Flamingo | 2022.2.1 Android SDK 33 Gradle 8.0.1 JDK 17 问题描述 笔者最近发现一个奇怪的事情。笔者的 Android Studio 的 Gradle 面板上居然除了用于测试的 task 之外&#xff0c;其它什…...

安全杂记 - 复现nodejs沙箱绕过

目录 一. 配置环境1.下载nodejs2.nodejs配置3.报错解决方法 二. nodej沙箱绕过1. vm模块2.使用this或引用类型来进行沙箱绕过 一. 配置环境 1.下载nodejs 官网&#xff1a;https://nodejs.org/en2.nodejs配置 安装nodejs的msi文件&#xff0c;默认配置一直下一步即可&#x…...

信息安全事件分类分级指南

范围 本指导性技术文件为信息安全事件的分类分级提供指导&#xff0c;用于信息安全事件的防范与处置&#xff0c;为事前准备、事中应对、事后处理 提供一个基础指南&#xff0c;可供信息系统和基础信息传输网络的运营和使用单位以及信息安全主管部门参考使用。 术语和定义 下…...

Vue系列第八篇:echarts绘制柱状图和折线图

本篇将使用echarts框架进行柱状图和折线图绘制。 目录 1.绘制效果 2.安装echarts 3.前端代码 4.后端代码 1.绘制效果 2.安装echarts // 安装echarts版本4 npm i -D echarts4 3.前端代码 src/api/api.js //业务服务调用接口封装import service from ../service.js //npm …...

SQL-每日一题【1164. 指定日期的产品价格】

题目 产品数据表: Products 写一段 SQL来查找在 2019-08-16 时全部产品的价格&#xff0c;假设所有产品在修改前的价格都是 10 。 以 任意顺序 返回结果表。 查询结果格式如下例所示。 示例 1: 解题思路 1.题目要求我们查找在 2019-08-16 时全部产品的价格&#xff0c;假设所…...

memcpy、memmove、memcmp、memset函数的作用与区别

一、memcpy与memmove 1、memcpy 作用&#xff1a;从source的位置开始向后复制num个字节的数据到destination的内存位置。 注意&#xff1a; memcpy() 函数在遇到 ’\0’ 的时候不会停下来(strcpy字符串拷贝函数在遇到’\0’的时候会停下来)&#xff1b;destination和source…...

socket 到底是个啥

我相信大家在面试过程中或多或少都会被问到这样一个问题&#xff1a;你能解释一下什么是 socket 吗 我记得我当初的回答很是浅显&#xff1a;socket 也叫套接字&#xff0c;用来负责不同主机程序之间的网络通信连接&#xff0c;socket 的表现方式由四元组&#xff08;ip地址&am…...

奥威BI—数字化转型首选,以数据驱动企业发展

奥威BI系统BI方案可以迅速构建企业级大数据分析平台&#xff0c;可以将大量数据转化为直观、易于理解的图表和图形&#xff0c;推动和促进数字化转型的进程&#xff0c;帮助企业更好地了解自身的运营状况&#xff0c;及时发现问题并采取相应的措施&#xff0c;提高运营效率和质…...

vue中swiper使用

1.引包 说明&#xff1a;导入相应js引css import "Swiper" from "swiper" import "swiper/css/swiper.css"; import "swiper/js/swiper"; 2.结构 说明&#xff1a;必要的结构使用&#xff1b;直接封装成一个组件 <template>…...

webpack与vite区别

webpack和Vite作为两种常用的前端构建工具,主要有以下几点区别: 构建速度 webpack采用“打包”的方式构建,需要将所有模块打包成几个大的bundle文件,构建速度较慢。 Vite采用了“按需编译”的方式,只在浏览器请求时才编译对应模块,启动速度更快。 dev server webpack dev s…...

GLSL用于图像处理

Pipeline 硬件处理顶点和片段的Pipeline 软件的输入 顶点着色器 顶点的glsl 输入–特殊全局变量 变量 类型 指定函数 描述 gl_ Vertex vec4 glVertex 顶点的全局空间坐标 gl_Color vec4 glColor 主颜色值 gl_SecondaryColor vec4 glSecondaryColor 辅助颜色值 gl_Normal …...

django filter 统计数量 按属性去重

在Django中&#xff0c;如果你想要根据某个属性对查询集进行去重并统计数量&#xff0c;你可以使用values()方法配合annotate()方法来实现。这里有两种常见的方法来完成这个需求&#xff1a; 方法1&#xff1a;使用annotate()和Count 假设你有一个模型Item&#xff0c;并且你想…...

论文浅尝 | 基于判别指令微调生成式大语言模型的知识图谱补全方法(ISWC2024)

笔记整理&#xff1a;刘治强&#xff0c;浙江大学硕士生&#xff0c;研究方向为知识图谱表示学习&#xff0c;大语言模型 论文链接&#xff1a;http://arxiv.org/abs/2407.16127 发表会议&#xff1a;ISWC 2024 1. 动机 传统的知识图谱补全&#xff08;KGC&#xff09;模型通过…...

什么是EULA和DPA

文章目录 EULA&#xff08;End User License Agreement&#xff09;DPA&#xff08;Data Protection Agreement&#xff09;一、定义与背景二、核心内容三、法律效力与责任四、实际应用与意义 EULA&#xff08;End User License Agreement&#xff09; 定义&#xff1a; EULA即…...

什么是Ansible Jinja2

理解 Ansible Jinja2 模板 Ansible 是一款功能强大的开源自动化工具&#xff0c;可让您无缝地管理和配置系统。Ansible 的一大亮点是它使用 Jinja2 模板&#xff0c;允许您根据变量数据动态生成文件、配置设置和脚本。本文将向您介绍 Ansible 中的 Jinja2 模板&#xff0c;并通…...

以光量子为例,详解量子获取方式

光量子技术获取量子比特可在室温下进行。该方式有望通过与名为硅光子学&#xff08;silicon photonics&#xff09;的光波导&#xff08;optical waveguide&#xff09;芯片制造技术和光纤等光通信技术相结合来实现量子计算机。量子力学中&#xff0c;光既是波又是粒子。光子本…...

服务器--宝塔命令

一、宝塔面板安装命令 ⚠️ 必须使用 root 用户 或 sudo 权限执行&#xff01; sudo su - 1. CentOS 系统&#xff1a; yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh2. Ubuntu / Debian 系统…...

Netty从入门到进阶(二)

二、Netty入门 1. 概述 1.1 Netty是什么 Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. Netty是一个异步的、基于事件驱动的网络应用框架&#xff0c;用于…...

scikit-learn机器学习

# 同时添加如下代码, 这样每次环境(kernel)启动的时候只要运行下方代码即可: # Also add the following code, # so that every time the environment (kernel) starts, # just run the following code: import sys sys.path.append(/home/aistudio/external-libraries)机…...

人工智能--安全大模型训练计划:基于Fine-tuning + LLM Agent

安全大模型训练计划&#xff1a;基于Fine-tuning LLM Agent 1. 构建高质量安全数据集 目标&#xff1a;为安全大模型创建高质量、去偏、符合伦理的训练数据集&#xff0c;涵盖安全相关任务&#xff08;如有害内容检测、隐私保护、道德推理等&#xff09;。 1.1 数据收集 描…...

通过MicroSip配置自己的freeswitch服务器进行调试记录

之前用docker安装的freeswitch的&#xff0c;启动是正常的&#xff0c; 但用下面的Microsip连接不上 主要原因有可能一下几个 1、通过下面命令可以看 [rootlocalhost default]# docker exec -it freeswitch fs_cli -x "sofia status profile internal"Name …...