SpringBoot实现SSMP整合

news2025/7/9 7:38:52

一、整合JUnit

1、Spring 整合 JUnit

核心注解有两个:

  1. @RunWith(SpringJUnit4ClassRunner.class) 是设置Spring专用于测试的类运行器(Spring程序执行程序有自己的一套独立的运行程序的方式,不能使用JUnit提供的类运行方式)
  2. @ContextConfiguration(classes = SpringConfig.class) 是用来设置Spring核心配置文件或配置类的(就是加载Spring的环境所需具体的环境配置)
//加载spring整合junit专用的类运行器
@RunWith(SpringJUnit4ClassRunner.class)
//指定对应的配置信息
@ContextConfiguration(classes = SpringConfig.class)
public class DemoServiceTestCase {
    //注入你要测试的对象
    @Autowired
    private DemoService demoService;
    @Test
    public void testGetById(){
        //执行要测试的对象对应的方法
        System.out.println(accountService.findById(2));
    }
}

2、SpringBoot 整合 JUnit

SpringBoot直接简化了 @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfig.class) 这两个几乎固定的注解。

package com.ty;

import com.ty.service.DemoService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootDemoApplicationTests {

    @Autowired
    private DemoService demoService;
    
    @Test
    public void getByIdTest(){
        demoService.getById();
    }
}

注意:

当然,如果测试类 SpringbootDemoApplicationTests 所在的包目录与 SpringBoot启动类 SpringbootDemoApplication 不相同,则启动时JUnit会找不到SpringBoot的启动类。报错 java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

在这里插入图片描述

解决方法: 将测试类 SpringbootDemoApplicationTests 所在的包目录与 SpringBoot启动类 SpringbootDemoApplication 调整一致,或通过 @SpringBootTest(classes = SpringbootDemoApplication.class) 指定SpringBoot启动类。

二、整合MyBatis

1、Spring 整合 MyBatis

  1. 首选引入MyBatis的一系列 Jar

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--1.导入mybatis与spring整合的jar包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!--导入spring操作数据库必选的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
    </dependencies>
    
  2. 数据库连接信息配置

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
    jdbc.username=root
    jdbc.password=root
    
  3. 定义mybatis专用的配置类

    //定义mybatis专用的配置类
    @Configuration
    public class MyBatisConfig {
    //    定义创建SqlSessionFactory对应的bean
        @Bean
        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
            //SqlSessionFactoryBean是由mybatis-spring包提供的,专用于整合用的对象
            SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
            //设置数据源替代原始配置中的environments的配置
            sfb.setDataSource(dataSource);
            //设置类型别名替代原始配置中的typeAliases的配置
            sfb.setTypeAliasesPackage("com.itheima.domain");
            return sfb;
        }
    //    定义加载所有的映射配置
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer(){
            MapperScannerConfigurer msc = new MapperScannerConfigurer();
            msc.setBasePackage("com.itheima.dao");
            return msc;
        }
    
    }
    
  4. Spring核心配置

    @Configuration
    @ComponentScan("com.itheima")
    @PropertySource("jdbc.properties")
    public class SpringConfig {
    }
    
  5. 配置Bean

    @Configuration
    public class JdbcConfig {
        @Value("${jdbc.driver}")
        private String driver;
        @Value("${jdbc.url}")
        private String url;
        @Value("${jdbc.username}")
        private String userName;
        @Value("${jdbc.password}")
        private String password;
    
        @Bean("dataSource")
        public DataSource dataSource(){
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(userName);
            ds.setPassword(password);
            return ds;
        }
    }
    

2、SpringBoot 整合 MyBatis

对比以上,SpringBoot简单很多。

  1. 首先导入MyBatis对应的starter mybatis-spring-boot-starter 和 数据库驱动 mysql-connector-java

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.0</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.27</version>
                <scope>runtime</scope>
            </dependency>
    
  2. 配置数据源相关信息

    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/ty
        username: root
        password: 123
    

    驱动类过时,提醒更换为com.mysql.cj.jdbc.Driver在这里插入图片描述

  3. 配置Entity和Dao,数据库SQL映射需要添加@Mapper被容器识别到

    package com.ty.entity;
    
    import lombok.Data;
    
    @Data
    public class TyUser {
    
        private Integer id;
    
        private String name;
    
        private Integer age;
    
    }
    
    
    	package com.ty.dao;
    	
    	import com.ty.entity.TyUser;
    	import org.apache.ibatis.annotations.Mapper;
    	import org.apache.ibatis.annotations.Select;
    	
    	@Mapper
    	public interface DemoDao {
    	
    	    @Select("select * from ty_user where id = #{id}")
    	    public TyUser getById(Integer id);
    	
    	}
    
  4. 通过测试类,注入 DemoService 即可调用。

    package com.ty;
    
    import com.ty.dao.DemoDao;
    import com.ty.entity.TyUser;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class SpringbootDemoApplicationTests {
        @Autowired
        private DemoDao demoDao;
    
        @Test
        public void getByIdTestDao(){
            TyUser byId = demoDao.getById(1);
            System.out.println(byId);
        }
    
    }
    

三、整合MyBatis-Plus

MyBaitsPlus(简称MP),国人开发的技术,符合中国人开发习惯

  1. 导入 mybatis_plus starter mybatis-plus-boot-starter

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3</version>
    </dependency>
    
  2. 配置数据源相关信息

    	spring:
    	  datasource:
    	    driver-class-name: com.mysql.jdbc.Driver
    	    url: jdbc:mysql://localhost:3306/ty
    	    username: root
    	    password: 123
    
  3. Dao 映射接口与实体类

    package com.example.springboot_mybatisplus_demo.dao;
    
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.example.springboot_mybatisplus_demo.entity.User;
    import org.apache.ibatis.annotations.Mapper;
    
    @Mapper
    public interface DemoDao extends BaseMapper<User> {
    }
    
    

    实体类名称与表名一致,可自动映射。当表名有前缀时,可在application.yml中配置表的通用前缀。

    package com.example.springboot_mybatisplus_demo.entity;
    
    import lombok.Data;
    
    @Data
    public class User {
    
        private Integer id;
    
        private String name;
    
        private Integer age;
    }
    
    
    mybatis-plus:
      global-config:
        db-config:
          table-prefix: ty_   #设置所有表的通用前缀名称为tbl_
    
  4. 编写测试类,注入DemoDao ,即可调用 mybatis_plus 提供的一系列方法。继承的BaseMapper的接口中帮助开发者预定了若干个常用的API接口,简化了通用API接口的开发工作。

    package com.example.springboot_mybatisplus_demo;
    
    import com.example.springboot_mybatisplus_demo.dao.DemoDao;
    import com.example.springboot_mybatisplus_demo.entity.User;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class SpringbootMybatisplusDemoApplicationTests {
    
        @Autowired
        private DemoDao demoDao;
    
        @Test
        public void getByIdTestDao(){
            User byId = demoDao.selectById(1);
            System.out.println(byId);
        }
    
    }
    
    

    在这里插入图片描述

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

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

相关文章

Deep Learning(0-14草履虫)

深度学习解决的问题 自动提取出最合适的特征 深度学习应用 神经网络基础 损失函数 前向传播 反向传播 绿色字体为正向传播i输入&#xff0c;红色字体为反向传播梯度 MAX门单元只把梯度传给最大的 神经网络整体架构 激活函数 隐藏层激活函数 一般选择Relu&#xff0c;sigmoid会…

STM32 IWDGWWDG

STM32 IWDG&WWDG 启动看门狗之后&#xff0c;看门狗是不能再被关闭的&#xff0c;除非发生复位。 IWDG独立看门狗 独立看门狗配置流程 开启LSI时钟&#xff0c;只有LSI时钟开启了&#xff0c;独立看门狗才能运行。 但是开启LSI的代码&#xff0c;并不需要我们来写&#xf…

【23种设计模式】装饰器模式

个人主页&#xff1a;金鳞踏雨 个人简介&#xff1a;大家好&#xff0c;我是金鳞&#xff0c;一个初出茅庐的Java小白 目前状况&#xff1a;22届普通本科毕业生&#xff0c;几经波折了&#xff0c;现在任职于一家国内大型知名日化公司&#xff0c;从事Java开发工作 我的博客&am…

WinSCP 集成 putty(也可以其他Terminal客户端)

putty 安装 官网安装地址 WinSCP集成putty&#xff08;也可以其他Terminal客户端&#xff09; 扩展 WinSCP是什么&#xff1f; WinSCP&#xff08;Windows Secure Copy Protocol&#xff09;是一个用于 Windows 操作系统的开源的 SFTP&#xff08;SSH File Transfer Protoc…

【Unity HDRP渲染管线下的WorleyUtilities文件,“Hash”函数】

Unity HDRP内置文件WorleyUtilities WorleyUtilities文件路径如下:文件代码如下然后转译到ShaderLab中:存档:WorleyUtilities文件路径如下: D:…\Library\PackageCache\com.unity.render-pipelines.high-definition@14.0.8\Runtime\Lighting\VolumetricClouds\WorleyUtili…

网络解析(二)

ICMP 报文有很多的类型,不同的类型有不同的代码。最常用的类型是主动请求为 8,主动请求的应答为 0。 ICMP 相当于网络世界的侦察兵。我讲了两种类型的 ICMP 报文,一种是主动探查的查询报文,一种异常报告的差错报文; ping 使用查询报文,Traceroute 使用差错报文。 IP和…

C++ 用户学习 Python 的最佳方法

对于很多是一名计算机科学专业的学生而言&#xff0c;很多入门是学习的C和 C&#xff0c;可能熟悉非常基本的 python 语法&#xff0c;以及 C 中相当高级的数据结构。现在想深入学习Python的话&#xff0c;光看很多在线教程可能没法有较大的提升&#xff0c;这里有一些针对C用户…

信息系统项目管理师第四版学习笔记——组织通用治理

组织战略 组织战略是组织高质量发展的总体谋略&#xff0c;是组织相关干系方就其发展达成一致认识的重要基础。组织战略是指组织针对其发展进行的全局性、长远性、纲领性目标的策划和选择。 战略目标是组织在一定的战略期内总体发展的总水平和总任务。它决定了组织在该战略期…

CodePlan

CodePlan论文解读 最近在看老师给的LLM-Agent论文&#xff0c;在这记录一下 CodePlan: Repository-level Coding using LLMs and Planning【论文】 旨在解决储存库级别的coding task&#xff0c;提出一个框架called CodePlan综合多步骤的编辑链&#xff0c;其中每个步骤都导…

华为---PPP协议简介及示例配置

PPP协议简介 PPP是Point-to-Point Protocol的简称&#xff0c;中文翻译为点到点协议。与以太网协议一样,PPP也是一个数据链路层协议。以太网协议定义了以太帧的格式&#xff0c;PPP协议也定义了自己的帧格式&#xff0c;这种格式的帧称为PPP帧。 利用PPP协议建立的二层网络称为…

云耀服务器L实例部署Typecho开源博客系统|华为云云耀云服务器L实例评测使用体验

云耀服务器L实例部署Typecho开源博客系统 文章目录 云耀服务器L实例部署Typecho开源博客系统1. 华为云云耀服务器L实例介绍2. Typecho2.1 Typecho 3. 部署华为云云耀服务器L实例3.1 云耀服务器L实例购买3.1.1 云耀服务器L实例初始化配置3.1.2 远程登录云耀服务器L实例 4. Typec…

基于MATLAB的图像条形码识别系统(matlab毕毕业设计2)

摘要 &#xff1a; 本论文旨在介绍一种基于MATLAB的图像条形码识别系统。该系统利用计算机视觉技术和图像处理算法&#xff0c;实现对不同类型的条形码进行准确识别。本文将详细介绍系统学习的流程&#xff0c;并提供详细教案&#xff0c;以帮助读者理解和实施该系统。 引言…

Git构建分布式版本控制系统

一、版本控制 1、概念&#xff1a; 版本控制&#xff08;Version Control&#xff09;&#xff0c;也被称为版本管理、源代码管理或代码控制&#xff0c;是一种系统和工具&#xff0c;用于跟踪和管理文件、数据或源代码的不同版本和历史记录&#xff0c;在软件开发、文档管理…

深入理解Huffman编码:原理、代码示例与应用

目录 ​编辑 介绍 Huffman编码的原理 信息理论背景 频率统计 Huffman树 Huffman编码的代码示例 数据结构 权重选择 Huffman编码生成 完整示例 完整代码 测试截图 Huffman编码的应用 总结 介绍 在这个数字时代&#xff0c;数据的有效压缩和传输变得至关重要。Hu…

【Linux】Ubunt20.04在vscode中使用Fira Code字体【教程】

【Linux】Ubunt20.04在vscode中使用Fira Code字体【教程】 文章目录 【Linux】Ubunt20.04在vscode中使用Fira Code字体【教程】1. 什么是Fira Code字体2. 安装Fira Code字体3. 配置vscodeReference 1. 什么是Fira Code字体 Fira Code&#xff1a;是一种带有编程连字的等宽字体。…

多组试验时正态分布标准差估计公式

本文介绍如何通过多组试验数据来估计正态总体的标准差. 一,各组试验次数相等 设正态总体X&#xff5e;N(μ,σ),其中均值μ和标准差σ未知.今有m组样本,每组样本大小n相等,其试验数据如下:求标准差σ的估计σ. 多组试验时正态分布标准差估计公式 - 百度学术

机器人制作开源方案 | 行星探测车概述

1. 功能描述 行星探测车&#xff08;Planetary Rover&#xff09;是一种用于进行科学探索和勘测任务的无人车辆&#xff0c;它们被设计成能够适应各种复杂的地形条件和极端环境&#xff0c;以便收集数据、拍摄照片、采集样本等。行星探测车通常包含以下主要组件和功能&#xff…

Ubuntu - 查看 IP 地址

要查看 Ubuntu 操作系统中的 IP 地址&#xff0c;可以使用 ip 命令或者 ifconfig 命令。以下是使用这两个命令的示例&#xff1a; 使用 ip 命令&#xff1a; 打开终端。 输入以下命令&#xff1a; ip a 这将显示网络接口信息&#xff0c;包括 IP 地址。通常&#xff0c;IP…

彩虹工具网程序开源未加密版源码_支持插件扩展 支持暗黑模式

2023全新UI彩虹站长在线工具箱系统源码下载 全开源版本 支持暗黑模式 支持高达72种站长工具、开发工具、娱乐工具等功能。本地调用API、自带免费API接口&#xff0c; 是一个多功能性工具程序支持后台管理、上传插件、添加增减删功能。 源码下载&#xff1a;https://download…

谈谈 Redis 主从复制模式

谈谈 Redis 主从复制模式 第一次主从节点同步是全量复制 接下来&#xff0c;我在具体介绍每一个阶段都做了什么。 第一阶段&#xff1a;建立链接、协商同步 执行了 replicaof 命令后&#xff0c;从服务器就会给主服务器发送 psync 命令&#xff0c;表示要进行数据同步。 psync…