spring之集成Mybatis
文章目录
- 一、实现步骤
- 1、准备数据库表
- 2、在IDEA中创建一个模块,并引入依赖
- 3、基于三层架构实现
- 4、编写pojo
- 5、编写mapper接口
- 6、编写mapper配置文件
- 7、编写service接口和service接口的实现类
- 8、编写jdbc.properties配置文件
- 9、编写mybatis-config.xml配置文件
- 10、编写spring.xml配置文件【配置地狱】
- 11、编写测试程序,添加事务,进行测试
一、实现步骤
1、准备数据库表
t_act:银行账户

2、在IDEA中创建一个模块,并引入依赖
- spring-context
- spring-jdbc
- mysql驱动
- mybatis
- mybatis-spring mybatis提供的与spring框架集成的依赖
- 德鲁伊连接池
- junit
为什么有了mybatis驱动还需要jdbc?
因为事务tx在jdbc包里

<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.32</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.20</version></dependency></dependencies>
3、基于三层架构实现
创建所有的包
com.powernode.bank.pojo
com.powernode.bank.mapper
com.powernode.bank.service
com.powernode.bank.service.impl

4、编写pojo
Account:属性私有化,提供公开的setter getter toString
public class Account {private String actno;private double balance;public Account(String actno, double balance) {this.actno = actno;this.balance = balance;}public Account() {}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 +'}';}
}
5、编写mapper接口
AccountMapper接口,定义方法
public interface AccountMapper {//该接口的实现类不需要写,是mybatis通过动态代理机制生成的实现类//查询所有的账户List<Account> seleteAllAccount();//根据actno查询指定账户Account selectByActno(String actno);//增加账户int insertAccount(Account account);//删除账户int deleteByActno(String actno);//修改账户int update(Account account);
}
6、编写mapper配置文件
在配置文件中配置命名空间,以及每一个方法对应的SQL
< mapper namespace=“com.powernode.bank.mapper.AccountMapper” >
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.powernode.bank.mapper.AccountMapper"><select id="selectAllAccount" resultType="account">select * from t_act</select><select id="selectByActno" resultType="account">select * from t_actwhere actno=#{actno};</select><insert id="insertAccount">insert into t_actvalues(#{actno},#{balance})</insert><delete id="deleteByActno">delete from t_actwhere actno=#{actno}</delete><update id="update">update t_actset balance=#{balance} where actno=#{actno}</update></mapper>
7、编写service接口和service接口的实现类
AccountService
public interface AccountService {//业务接口int save(Account account);int deleteByActno(String actno);int modify(Account account);Account getByActno(String actno);List<Account> getAll();void transfer(String fromActno,String toActno,double money);
}
AccountServiceImpl
注意一定要进行AccountServiceImpl Bean实例化:@Service(“accountService”)
以及一定要注入AccountMapper Bean注入: @Autowired
@Service("accountService")
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountMapper mapper;@Overridepublic int save(Account account) {int i = mapper.insertAccount(account);return i;}@Overridepublic int deleteByActno(String actno) {int i = mapper.deleteByActno(actno);return i;}@Overridepublic int modify(Account account) {mapper.update(account);return 0;}@Overridepublic Account getByActno(String actno) {return mapper.selectByActno(actno);}@Overridepublic List<Account> getAll() {return mapper.seleteAllAccount();}@Overridepublic void transfer(String fromActno, String toActno, double money) {Account fromAct = mapper.selectByActno(fromActno);Account toAct = mapper.selectByActno(toActno);if(fromAct.getBalance()<money){throw new RuntimeException("余额不足");}fromAct.setBalance(fromAct.getBalance()-money);toAct.setBalance(toAct.getBalance()+money);int count = mapper.update(fromAct);count += mapper.update(toAct);if(count==2){System.out.println("转账成功");}else{throw new RuntimeException("转账失败");}}
}
8、编写jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dududu?useSSL=false
jdbc.username=root
jdbc.password=123456
9、编写mybatis-config.xml配置文件
这个文件可以没有,大部分的配置可以转移到spring配置文件中
如果遇到mybatis相关的系统级配置,还是需要这个文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--设置日志输出语句,显示相应操作的sql语名--><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings>
</configuration>
10、编写spring.xml配置文件【配置地狱】
1、组件扫描
2、引入外部的属性文件
3、数据源
4、SqlSessionFactoryBean配置
注入mybatis核心配置文件
指定别名包
注入数据源
5、Mapper扫描配置器(主要扫描mapper接口生成代理类)
扫描指定的包
6、事务管理器 DataSourceTransactionManager
注入数据源
7、启用事务注解【启用之后在业务实现类当中添加注解@Transactional 事务才会起作用】
注入事务管理器
<?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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!--组件扫描--><!--<context:component-scan base-package="com.powernode.bank"/>--><!--在spring的核心配置文件中引入其他的子spring配置文件--><context:component-scan base-package="com.powernode.bank"></context:component-scan><context:property-placeholder location="jdbc.properties"></context:property-placeholder><!--数据源--><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.username}"/><property name="password" value="${jdbc.password}"/></bean><!--配置SqlSessionFactoryBean--><bean class="org.mybatis.spring.SqlSessionFactoryBean"><!--注入数据源--><property name="dataSource" ref="dataSource"/><!--指定mybatis核心配置文件--><property name="configLocation" value="mybatis-config.xml"/><!--指定别名--><property name="typeAliasesPackage" value="com.powernode.bank.pojo"/></bean><!--Mapper扫描配置器,主要扫描Mapper接口,生成代理类--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.powernode.bank.mapper"/></bean><!--事务管理器--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--启用事务注解--><tx:annotation-driven transaction-manager="txManager"/></beans>
11、编写测试程序,添加事务,进行测试
@Testpublic void testSM(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");AccountService accountService = ac.getBean("accountService",AccountService.class);//accountService.transfer("act_001","act_002",2000);accountService.save(new Account("act_005",20));List<Account> AccountList = accountService.getAll();AccountList.forEach(list->{System.out.println("账号为:"+list.getActno()+",账户余额为:"+list.getBalance());});}

相关文章:
spring之集成Mybatis
文章目录一、实现步骤1、准备数据库表2、在IDEA中创建一个模块,并引入依赖3、基于三层架构实现4、编写pojo5、编写mapper接口6、编写mapper配置文件7、编写service接口和service接口的实现类8、编写jdbc.properties配置文件9、编写mybatis-config.xml配置文件10、编…...
【面试宝典】准备面试了~集合
1、ArrayList和linkedList的区别 它们都是继承自 Collection。 ArrayList 是基于数组的,在使用查询的时候效率比较高,但删除效率却非常低,因为它需要重新排数组中的所有数据。 LinkList底层是一个双链表,在添加和删除元素时更好…...
华为OD机试真题Python实现【GPU 调度】真题+解题思路+代码(20222023)
GPU 调度 题目 为了充分发挥 GPU 算力, 需要尽可能多的将任务交给 GPU 执行, 现在有一个任务数组, 数组元素表示在这1s内新增的任务个数, 且每秒都有新增任务, 假设 GPU 最多一次执行n个任务, 一次执行耗时1s, 在保证 GPU 不空闲的情况下,最少需要多长时间执行完成。…...
gcc编译C源程序
一、安装 在Linux下,一般使用gcc或arm-linux-gcc交叉编译器来编译程序。在Ubuntu环境下,我们可以使用以下apt-get命令来安装这些编译程序。 apt-get install gcc apt-get install gcc-arm-linux-gnueabi 安装完毕后,使用以下命令查看编译器…...
Tina_Linux_各平台多媒体格式_支持列表_new
Tina Linux 各平台多媒体格式支持列表 1 概述 1.1 编写目的 本文档将介绍Allwinner Tina Linux 系统各个芯片平台支持的多媒体格式,旨在帮助软件开发工程师、技术支持工程师查找各芯片平台支持哪些多媒体格式。 1.2 适用范围 Tina Linux v3.5 及以上版本。 1.…...
归并排序及其应用
归并排序算法基于分而治之的概念,具体来说就是遍历一棵树,归并的过程是一个后序执行的动作。 由于我们知道每个子部分在合并后都是有序的,我们可以利用这个特性来解决一些问题。 上图可视化了merge sort algorithm的过程,我们很容…...
【PAT甲级题解记录】1007 Maximum Subsequence Sum (25 分)
【PAT甲级题解记录】1007 Maximum Subsequence Sum (25 分) 前言 Problem:1007 Maximum Subsequence Sum (25 分) Tags:DP Difficulty:剧情模式 想流点汗 想流点血 死而无憾 Address:1007 Maximum Subsequence Sum (25 分) 问题描…...
华为OD机试真题Python实现【 最小叶子节点】真题+解题思路+代码(20222023)
最小叶子节点 题目 二叉树也可以用数组来存储, 给定一个数组,树的根节点的值储存在下标1, 对于储存在下标n的节点,他的左子节点和右子节点分别储存在下标2*n和2*n+1, 并且我们用-1代表一个节点为空, 给定一个数组存储的二叉树, 试求从根节点到最小的叶子节点的路径, …...
mars3d动态轨迹DynamicRoamLine,如何获取实时运⾏的经纬度
问题 1.期望 实现 实时显示经纬度、⾼度,做电⼦围栏报警判断 2.第⼀步就是要,获取实时运⾏的经纬度信息、⾼度信息,然后通过算法做电⼦围栏判断 3.使⽤了参数getOverPositions,发现返回的不是经纬度 相关链接 http://mars3d.cn//e…...
jvm常识
Jvm工作原理学习笔记0126一、JVM的生命周期1.JVM实例对应了一个独立运行的java程序它是进程级别a)启动。启动一个Java程序时,一个JVM实例就产生了,任何一个拥有public static void main(String[] args)函数的class都可以作为JVM实例运行的起点b)运行。ma…...
PHP部署、nginx与PHP的整合、PHP动态添加模块
文章目录前言一、基本知识1.php介绍2.PHP能做什么3.web工作原理4.PHP脚本主要用于领域5.php其他相关信息6.memcache介绍二、php的源码安装1.php安装2.php配置三、nginx与php整合四、php动态扩展模块(memcache模块)前言 一、基本知识 1.php介绍 官方下载…...
SpringCloud与SpringBoot的版本对应
一、SpringCloud与SpringBoot的版本对应 SpringCloud版本 SpringBoot版本 2021.0.1-SNAPSHOT Spring Boot >2.6.4-SNAPSHOT and <2.7.0-M1 2021.0.0 Spring Boot >2.6.1 and <2.6.4-SNAPSHOT 2021.0.0-RC1 Spring Boot >2.6.0-RC1 and <2.6.1 2021.0.0-M3 Sp…...
华为OD机试题,用 Java 解【N 进制减法】问题
最近更新的博客 华为OD机试 - 猴子爬山 | 机试题算法思路 【2023】华为OD机试 - 分糖果(Java) | 机试题算法思路 【2023】华为OD机试 - 非严格递增连续数字序列 | 机试题算法思路 【2023】华为OD机试 - 消消乐游戏(Java) | 机试题算法思路 【2023】华为OD机试 - 组成最大数…...
Linux->进程概念于基本创建
1. 进程基本概念 当一个可执行程序被加载到内存当中,并由操作系统将其管理起来,此时这个程序就被称之为进程。也就是下方的: 程序的一个执行实例,正在执行的程序等 担当分配系统资源(CPU时间,内存ÿ…...
【MySQL】5.7版本解压安装配置
前言 之所以使用解压版本,而不使用exe安装,因为exe的安装方式删除过于麻烦!!! 如果安装MySQL过程中,出错了或者想重新在来一把,删除mysql服务即可 sc delete mysql # 删除已经安装好的Mysql&a…...
c++类对象数据成员和虚函数的内存布局
一直想搞清楚类对象的数据成员和虚函数的内存布局,今天刚好有时间,所以就写了个demo查看了一下具体的内存布局情况(使用的编译器为微软的)。下面是自己demo的代码:#include <iostream> #include <windows.h&g…...
Python 模块和包
1. 模块和包 **容器:**列表、元组、字符串、字典等,对数据的封装**函数:**对语句的封装**类:**对方法和属性的封装,即对函数和数据的封装 而模块(module)就是个程序,一个.py 文件&…...
Java零基础专栏——面向对象
1 面向对象思想1.1 什么是面向对象?2 类和对象2.1 类和对象的理解2.2 类的定义2.3定义类的补充注意事项2.4 对象的使用2.5 练习3 封装3.1 封装思想3.1.1 封装概述3.1.2 封装的步骤3.1.3 封装代码实现3.2 private关键字3.3 练习—private的使用4 构造方法4.1 构造方法…...
离散无记忆与有记忆信源的序列熵
本专栏包含信息论与编码的核心知识,按知识点组织,可作为教学或学习的参考。markdown版本已归档至【Github仓库:information-theory】,需要的朋友们自取。或者公众号【AIShareLab】回复 信息论 也可获取。 文章目录离散无记忆信源的…...
算法该不该刷?如何高效刷算法?
一、算法该不该刷?最近有小伙伴向我咨询一个问题,就是算法该不该刷,该如何刷算法呢?这个问题可谓太大众化了,只要你去某乎、某度搜索一下相关的解答,会有无数种回答,可见这个问题困扰了多少学习…...
MPNet:旋转机械轻量化故障诊断模型详解python代码复现
目录 一、问题背景与挑战 二、MPNet核心架构 2.1 多分支特征融合模块(MBFM) 2.2 残差注意力金字塔模块(RAPM) 2.2.1 空间金字塔注意力(SPA) 2.2.2 金字塔残差块(PRBlock) 2.3 分类器设计 三、关键技术突破 3.1 多尺度特征融合 3.2 轻量化设计策略 3.3 抗噪声…...
(十)学生端搭建
本次旨在将之前的已完成的部分功能进行拼装到学生端,同时完善学生端的构建。本次工作主要包括: 1.学生端整体界面布局 2.模拟考场与部分个人画像流程的串联 3.整体学生端逻辑 一、学生端 在主界面可以选择自己的用户角色 选择学生则进入学生登录界面…...
SciencePlots——绘制论文中的图片
文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了:一行…...
Python如何给视频添加音频和字幕
在Python中,给视频添加音频和字幕可以使用电影文件处理库MoviePy和字幕处理库Subtitles。下面将详细介绍如何使用这些库来实现视频的音频和字幕添加,包括必要的代码示例和详细解释。 环境准备 在开始之前,需要安装以下Python库:…...
学习STC51单片机32(芯片为STC89C52RCRC)OLED显示屏2
每日一言 今天的每一份坚持,都是在为未来积攒底气。 案例:OLED显示一个A 这边观察到一个点,怎么雪花了就是都是乱七八糟的占满了屏幕。。 解释 : 如果代码里信号切换太快(比如 SDA 刚变,SCL 立刻变&#…...
JS手写代码篇----使用Promise封装AJAX请求
15、使用Promise封装AJAX请求 promise就有reject和resolve了,就不必写成功和失败的回调函数了 const BASEURL ./手写ajax/test.jsonfunction promiseAjax() {return new Promise((resolve, reject) > {const xhr new XMLHttpRequest();xhr.open("get&quo…...
省略号和可变参数模板
本文主要介绍如何展开可变参数的参数包 1.C语言的va_list展开可变参数 #include <iostream> #include <cstdarg>void printNumbers(int count, ...) {// 声明va_list类型的变量va_list args;// 使用va_start将可变参数写入变量argsva_start(args, count);for (in…...
毫米波雷达基础理论(3D+4D)
3D、4D毫米波雷达基础知识及厂商选型 PreView : https://mp.weixin.qq.com/s/bQkju4r6med7I3TBGJI_bQ 1. FMCW毫米波雷达基础知识 主要参考博文: 一文入门汽车毫米波雷达基本原理 :https://mp.weixin.qq.com/s/_EN7A5lKcz2Eh8dLnjE19w 毫米波雷达基础…...
论文阅读笔记——Muffin: Testing Deep Learning Libraries via Neural Architecture Fuzzing
Muffin 论文 现有方法 CRADLE 和 LEMON,依赖模型推理阶段输出进行差分测试,但在训练阶段是不可行的,因为训练阶段直到最后才有固定输出,中间过程是不断变化的。API 库覆盖低,因为各个 API 都是在各种具体场景下使用。…...
数据结构第5章:树和二叉树完全指南(自整理详细图文笔记)
名人说:莫道桑榆晚,为霞尚满天。——刘禹锡(刘梦得,诗豪) 原创笔记:Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊) 上一篇:《数据结构第4章 数组和广义表》…...
