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

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中创建一个模块&#xff0c;并引入依赖3、基于三层架构实现4、编写pojo5、编写mapper接口6、编写mapper配置文件7、编写service接口和service接口的实现类8、编写jdbc.properties配置文件9、编写mybatis-config.xml配置文件10、编…...

【面试宝典】准备面试了~集合

1、ArrayList和linkedList的区别 它们都是继承自 Collection。 ArrayList 是基于数组的&#xff0c;在使用查询的时候效率比较高&#xff0c;但删除效率却非常低&#xff0c;因为它需要重新排数组中的所有数据。 LinkList底层是一个双链表&#xff0c;在添加和删除元素时更好…...

华为OD机试真题Python实现【GPU 调度】真题+解题思路+代码(20222023)

GPU 调度 题目 为了充分发挥 GPU 算力, 需要尽可能多的将任务交给 GPU 执行, 现在有一个任务数组, 数组元素表示在这1s内新增的任务个数, 且每秒都有新增任务, 假设 GPU 最多一次执行n个任务, 一次执行耗时1s, 在保证 GPU 不空闲的情况下,最少需要多长时间执行完成。…...

gcc编译C源程序

一、安装 在Linux下&#xff0c;一般使用gcc或arm-linux-gcc交叉编译器来编译程序。在Ubuntu环境下&#xff0c;我们可以使用以下apt-get命令来安装这些编译程序。 apt-get install gcc apt-get install gcc-arm-linux-gnueabi 安装完毕后&#xff0c;使用以下命令查看编译器…...

Tina_Linux_各平台多媒体格式_支持列表_new

Tina Linux 各平台多媒体格式支持列表 1 概述 1.1 编写目的 本文档将介绍Allwinner Tina Linux 系统各个芯片平台支持的多媒体格式&#xff0c;旨在帮助软件开发工程师、技术支持工程师查找各芯片平台支持哪些多媒体格式。 1.2 适用范围 Tina Linux v3.5 及以上版本。 1.…...

归并排序及其应用

归并排序算法基于分而治之的概念&#xff0c;具体来说就是遍历一棵树&#xff0c;归并的过程是一个后序执行的动作。 由于我们知道每个子部分在合并后都是有序的&#xff0c;我们可以利用这个特性来解决一些问题。 上图可视化了merge sort algorithm的过程&#xff0c;我们很容…...

【PAT甲级题解记录】1007 Maximum Subsequence Sum (25 分)

【PAT甲级题解记录】1007 Maximum Subsequence Sum (25 分) 前言 Problem&#xff1a;1007 Maximum Subsequence Sum (25 分) Tags&#xff1a;DP Difficulty&#xff1a;剧情模式 想流点汗 想流点血 死而无憾 Address&#xff1a;1007 Maximum Subsequence Sum (25 分) 问题描…...

华为OD机试真题Python实现【 最小叶子节点】真题+解题思路+代码(20222023)

最小叶子节点 题目 二叉树也可以用数组来存储, 给定一个数组,树的根节点的值储存在下标1, 对于储存在下标n的节点,他的左子节点和右子节点分别储存在下标2*n和2*n+1, 并且我们用-1代表一个节点为空, 给定一个数组存储的二叉树, 试求从根节点到最小的叶子节点的路径, …...

mars3d动态轨迹DynamicRoamLine,如何获取实时运⾏的经纬度

问题 1.期望 实现 实时显示经纬度、⾼度&#xff0c;做电⼦围栏报警判断 2.第⼀步就是要&#xff0c;获取实时运⾏的经纬度信息、⾼度信息&#xff0c;然后通过算法做电⼦围栏判断 3.使⽤了参数getOverPositions&#xff0c;发现返回的不是经纬度 相关链接 http://mars3d.cn//e…...

jvm常识

Jvm工作原理学习笔记0126一、JVM的生命周期1.JVM实例对应了一个独立运行的java程序它是进程级别a)启动。启动一个Java程序时&#xff0c;一个JVM实例就产生了&#xff0c;任何一个拥有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动态扩展模块&#xff08;memcache模块&#xff09;前言 一、基本知识 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. 进程基本概念 当一个可执行程序被加载到内存当中&#xff0c;并由操作系统将其管理起来&#xff0c;此时这个程序就被称之为进程。也就是下方的&#xff1a; 程序的一个执行实例&#xff0c;正在执行的程序等 担当分配系统资源&#xff08;CPU时间&#xff0c;内存&#xff…...

【MySQL】5.7版本解压安装配置

前言 之所以使用解压版本&#xff0c;而不使用exe安装&#xff0c;因为exe的安装方式删除过于麻烦&#xff01;&#xff01;&#xff01; 如果安装MySQL过程中&#xff0c;出错了或者想重新在来一把&#xff0c;删除mysql服务即可 sc delete mysql # 删除已经安装好的Mysql&a…...

c++类对象数据成员和虚函数的内存布局

一直想搞清楚类对象的数据成员和虚函数的内存布局&#xff0c;今天刚好有时间&#xff0c;所以就写了个demo查看了一下具体的内存布局情况&#xff08;使用的编译器为微软的&#xff09;。下面是自己demo的代码&#xff1a;#include <iostream> #include <windows.h&g…...

Python 模块和包

1. 模块和包 **容器&#xff1a;**列表、元组、字符串、字典等&#xff0c;对数据的封装**函数&#xff1a;**对语句的封装**类&#xff1a;**对方法和属性的封装&#xff0c;即对函数和数据的封装 而模块&#xff08;module&#xff09;就是个程序&#xff0c;一个.py 文件&…...

Java零基础专栏——面向对象

1 面向对象思想1.1 什么是面向对象&#xff1f;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 构造方法…...

离散无记忆与有记忆信源的序列熵

本专栏包含信息论与编码的核心知识&#xff0c;按知识点组织&#xff0c;可作为教学或学习的参考。markdown版本已归档至【Github仓库&#xff1a;information-theory】&#xff0c;需要的朋友们自取。或者公众号【AIShareLab】回复 信息论 也可获取。 文章目录离散无记忆信源的…...

算法该不该刷?如何高效刷算法?

一、算法该不该刷&#xff1f;最近有小伙伴向我咨询一个问题&#xff0c;就是算法该不该刷&#xff0c;该如何刷算法呢&#xff1f;这个问题可谓太大众化了&#xff0c;只要你去某乎、某度搜索一下相关的解答&#xff0c;会有无数种回答&#xff0c;可见这个问题困扰了多少学习…...

谷歌浏览器插件

项目中有时候会用到插件 sync-cookie-extension1.0.0&#xff1a;开发环境同步测试 cookie 至 localhost&#xff0c;便于本地请求服务携带 cookie 参考地址&#xff1a;https://juejin.cn/post/7139354571712757767 里面有源码下载下来&#xff0c;加在到扩展即可使用FeHelp…...

React 第五十五节 Router 中 useAsyncError的使用详解

前言 useAsyncError 是 React Router v6.4 引入的一个钩子&#xff0c;用于处理异步操作&#xff08;如数据加载&#xff09;中的错误。下面我将详细解释其用途并提供代码示例。 一、useAsyncError 用途 处理异步错误&#xff1a;捕获在 loader 或 action 中发生的异步错误替…...

.Net框架,除了EF还有很多很多......

文章目录 1. 引言2. Dapper2.1 概述与设计原理2.2 核心功能与代码示例基本查询多映射查询存储过程调用 2.3 性能优化原理2.4 适用场景 3. NHibernate3.1 概述与架构设计3.2 映射配置示例Fluent映射XML映射 3.3 查询示例HQL查询Criteria APILINQ提供程序 3.4 高级特性3.5 适用场…...

蓝牙 BLE 扫描面试题大全(2):进阶面试题与实战演练

前文覆盖了 BLE 扫描的基础概念与经典问题蓝牙 BLE 扫描面试题大全(1)&#xff1a;从基础到实战的深度解析-CSDN博客&#xff0c;但实际面试中&#xff0c;企业更关注候选人对复杂场景的应对能力&#xff08;如多设备并发扫描、低功耗与高发现率的平衡&#xff09;和前沿技术的…...

MySQL 8.0 OCP 英文题库解析(十三)

Oracle 为庆祝 MySQL 30 周年&#xff0c;截止到 2025.07.31 之前。所有人均可以免费考取原价245美元的MySQL OCP 认证。 从今天开始&#xff0c;将英文题库免费公布出来&#xff0c;并进行解析&#xff0c;帮助大家在一个月之内轻松通过OCP认证。 本期公布试题111~120 试题1…...

数据库分批入库

今天在工作中&#xff0c;遇到一个问题&#xff0c;就是分批查询的时候&#xff0c;由于批次过大导致出现了一些问题&#xff0c;一下是问题描述和解决方案&#xff1a; 示例&#xff1a; // 假设已有数据列表 dataList 和 PreparedStatement pstmt int batchSize 1000; // …...

高防服务器能够抵御哪些网络攻击呢?

高防服务器作为一种有着高度防御能力的服务器&#xff0c;可以帮助网站应对分布式拒绝服务攻击&#xff0c;有效识别和清理一些恶意的网络流量&#xff0c;为用户提供安全且稳定的网络环境&#xff0c;那么&#xff0c;高防服务器一般都可以抵御哪些网络攻击呢&#xff1f;下面…...

Element Plus 表单(el-form)中关于正整数输入的校验规则

目录 1 单个正整数输入1.1 模板1.2 校验规则 2 两个正整数输入&#xff08;联动&#xff09;2.1 模板2.2 校验规则2.3 CSS 1 单个正整数输入 1.1 模板 <el-formref"formRef":model"formData":rules"formRules"label-width"150px"…...

项目部署到Linux上时遇到的错误(Redis,MySQL,无法正确连接,地址占用问题)

Redis无法正确连接 在运行jar包时出现了这样的错误 查询得知问题核心在于Redis连接失败&#xff0c;具体原因是客户端发送了密码认证请求&#xff0c;但Redis服务器未设置密码 1.为Redis设置密码&#xff08;匹配客户端配置&#xff09; 步骤&#xff1a; 1&#xff09;.修…...

ip子接口配置及删除

配置永久生效的子接口&#xff0c;2个IP 都可以登录你这一台服务器。重启不失效。 永久的 [应用] vi /etc/sysconfig/network-scripts/ifcfg-eth0修改文件内内容 TYPE"Ethernet" BOOTPROTO"none" NAME"eth0" DEVICE"eth0" ONBOOT&q…...