Springboot整合第三方技术及整合案例

news2024/10/10 10:24:15

Springboot整合第三方技术

  • 一、Springboot整合Junit
    • 1、步骤
    • 2、classes属性
  • 二、整合Mybatis
    • 1、步骤
    • 2、常见问题
  • 三、整合Mybatis-plus
    • 1、步骤
    • 2、常见配置
  • 四、整合Druid
    • 1、步骤
  • 五、整合案例-数据层(基础的CRUD)
    • 1、创建springboot项目
    • 手工导入starter坐标
    • 2、配置数据源与MybatisPlus对应的配置
    • 3、新建实体类
    • 4、继承BaseMapper并指定泛型
    • 5、制作测试类测试结果
    • 备注
      • 1、为方便调试可以开启MybatisPlus的日志
      • 2、分页功能
      • 3、条件查询功能
  • 六、整合案例-业务层
    • 1、Service接口名称定义成业务名称,并与Dao接口名称进行区分
    • 2、制作测试类测试Service功能是否有效
    • 3、业务层快速开发方案
  • 七、整合案例-表现层
    • 1、功能测试、表现层接口开发
    • 2、表现层消息一致性处理


整合第三方技术通用方式

  • 导入对应的starter
  • 根据提供的配置格式,配置非默认值对应的配置项

一、Springboot整合Junit

1、步骤

  • 1、导入测试对应的starter
  • 2、测试类使用@SpringBootTest修饰
  • 3、使用自动装配的形式添加要测试的对象
@SpringBootTest
class Springboot02ApplicationTests {

    @Autowired
    private BookService bookService;
    @Test
    void contextLoads() {
        bookService.save();
    }

}
  • 注解:@SpringBootTest
  • 类型:测试类注解
  • 位置:测试类定义上方
  • 作用:设置JUnit加载的SpringBoot启动类
  • example:
@SpringBootTest
class Springboot02ApplicationTests {}

2、classes属性

  • 测试类如果存在于引导类所在包或子包中无需指定引导类
  • 测试类如果不存在于引导类所在的包或子包中需要通过classes属性指定引导类
@SpringBootTest(classes = Springboot02Application.class)
class Springboot02ApplicationTests {
  • 相关属性 :classes:设置SpringBoot启动类

如果测试类在SpringBoot启动类的包或子包中,可以省略启动类的设置,也就是省略classes的设定

二、整合Mybatis

1、步骤

  • 1、创建新模块,选择Spring初始化,并配置模块相关基础信息
  • 2、选择当前模块需要使用的技术集(Mybatis、MySQL)
  • 3、设置数据源参数
server:
  port: 80

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot-demo?serverTimezone=GMT%2B8
    username: root
    password: 123
    type: com.alibaba.druid.pool.DruidDataSource

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tb_
  • 4、定义数据层接口与映射配置

数据库SQL映射需要添加@Mapper被容器识别到

@Mapper
public interface SportDao {
    @Select("select *from tb_sport where id = #{id}")
    public Sport getById(Integer id);
}
  • 5、测试类中注入dao接口,测试功能
@SpringBootTest
class Springboot04ApplicationTests {

    @Autowired
    private SportDao sportDao;
    @Test
    void contextLoads() {
        System.out.println(sportDao.getById(1));
    }

}

2、常见问题

1、MySQL 8.X 驱动强制要求设置时区

  • 修改url,添加serverTimezone设定
  • 修改MySQL数据库配置

2、驱动过时,提醒更换为driver-class-name: com.mysql.jdbc.Driver

Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

driver-class-name: com.mysql.jdbc.Driver改为driver-class-name: com.mysql.cj.jdbc.Driver

三、整合Mybatis-plus

1、步骤

  • 1、手动添加SpringBoot整合Mybatis-plus的坐标,可以通过mvnrepository获取
		 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>

由于SpringBoot中未收录Mybatis-plus的坐标版本,需要指定对应的Version

  • 2、定义数据层接口与映射配置,继承BaseMapper
@Mapper
public interface SportDao extends BaseMapper<Sport> {
}
  • 3、当需要使用的第三方技术无法通过勾选确定时,需要手工添加坐标

2、常见配置

配置数据源与MybatisPlus对应的基础配置(id生成策略使用数据库自增策略)
在这里插入图片描述

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tb_
      id-type: auto

四、整合Druid

1、步骤

  • 1、指定数据源类型
    通用型:
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/sport_db
    username: root
    password: 123
    type: com.alibaba.druid.pool.DruidDataSource
  • 导入Druid对应的starter
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
  • 变更Druid的配置方式
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/sport_db?serverTimezone=UTC
      username: root
      password: 123

五、整合案例-数据层(基础的CRUD)

1、创建springboot项目

在这里插入图片描述

手工导入starter坐标

<dependency>
	<groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.15</version>
</dependency>

2、配置数据源与MybatisPlus对应的配置

server:
  port: 80

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot-demo?serverTimezone=GMT%2B8
    username: root
    password: 123
    type: com.alibaba.druid.pool.DruidDataSource

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tb_
      id-type: auto

3、新建实体类

@Data
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}

4、继承BaseMapper并指定泛型

@Mapper
public interface BookDao extends BaseMapper<Book> {
}

5、制作测试类测试结果

@SpringBootTest
public class BookDaoTest {
    @Autowired
    private BookDao bookDao;

    @Test
    void testGetById(){
        System.out.println(bookDao.selectById(1));
    }

    @Test
    void testSave(){
        Book book = new Book();
        book.setType("测试123");
        book.setName("测试123");
        book.setDescription("测试123");
        bookDao.insert(book);
    }
    @Test
    void testUpdate(){
        Book book = new Book();
        book.setId(2);
        book.setType("技术");
        book.setName("java从入门到精通");
        book.setDescription("没用");
        bookDao.updateById(book);
    }
    @Test
    void testDelete(){
        bookDao.deleteById(2);
    }
    @Test
    void testGetAll(){
        bookDao.selectList(null);
    }
}

备注

1、为方便调试可以开启MybatisPlus的日志

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2、分页功能

  • 分页操作需要设定分页对象IPage
 	@Test
    void testGetPage(){
        IPage page = new Page(2,2);
        bookDao.selectPage(page,null);
    }
  • IPage对象中封装了分页操作中的所有数据
    • 数据
    • 当前页码值
    • 每页数据总量
    • 最大页码值
    • 数据总量
  • 分页操作是在MybatisPlus的常规操作基础上增强得到,内部是动态的拼写SQL语句,因此需要增强对应的功能,使用MybatisPlus拦截器实现
@Configuration
public class MPConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor  = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

3、条件查询功能

  • 使用QueryWrapper对象封装查询条件,推荐使用LambdaQueryWrapper对象,所有查询操作封装成方法调用
	@Test
    void testGetBy(){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name","三");
        bookDao.selectList(queryWrapper);
    }
	@Test
    void testGetBy1(){
       IPage page = new Page(1,2);
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.like(Book::getName,"三");
        bookDao.selectPage(page,lqw);
    }
  • 支持动态拼写查询条件
	@Test
    void testGetBy1(){
       IPage page = new Page(1,2);
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(Name),Book::getName,"三");
        bookDao.selectPage(page,lqw);
    }

六、整合案例-业务层

1、Service接口名称定义成业务名称,并与Dao接口名称进行区分

  • 接口定义
public interface BookService {
    Boolean save(Book book  );
    Boolean update(Book book);
    Boolean delete(Integer id);
    Book getById(Integer id);
    List<Book> getAll();
}
  • 实现类定义
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;


    @Override
    public Boolean save(Book book) {
		//将业务层接口转化为操作状态
        return bookDao.insert(book) > 0;
    }

    @Override
    public Boolean update(Book book) {

        return bookDao.updateById(book)>0   ;
    }

    @Override
    public Boolean delete(Integer id) {
        return bookDao.deleteById(id)>0;
    }

    @Override
    public Book getById(Integer id) {
        return bookDao.selectById(id);
    }

    @Override
    public List<Book> getAll() {

        return bookDao.selectList(null);
    }
}

2、制作测试类测试Service功能是否有效

  • 测试类定义
@SpringBootTest
public class BookServiceTestCase {
    @Autowired
    private BookService bookService;

    @Test
    void testGetById(){
        System.out.println(bookService.getById(4));
    }
    @Test
    void testUpdate(){
        Book book = new Book();
        book.setId(8);
        book.setType("技术");
        book.setName("java从入门到精通");
        book.setDescription("没用");
        bookService.update(book);
    }
}

3、业务层快速开发方案

  • 使用MyBatisplus提供业务层通用接口(IService)与业务层通用实现类(ServiceImpl<M,T>)
public interface IBookService extends IService<Book> {
    //追加的操作与原始操作通过名称区分,功能类似
    Boolean delete(Integer id);
    Boolean insert(Book book);
}
public class IBookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {
}
  • 在通用类基础上做功能重载或功能追加
  • 注意重载时不要覆盖原始操作,避免原始提供的功能丢失

七、整合案例-表现层

1、功能测试、表现层接口开发

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private IBookService bookService;
    @GetMapping
    public List<Book> getAll(){
        return bookService.list();
    }
    @PostMapping
    public Boolean save(Book book){
        return bookService.save(book);
    }
//    @PutMapping
//    public Boolean update(Book book){
//        return bookService.update(book);
//    }
//    @DeleteMapping("{id}")
//    public Boolean delete(@PathVariable Integer id){
//        return bookService.delete(id);
//    }
    @GetMapping("{id}")
    public Book getById(@PathVariable Integer id){
        return bookService.getById(id);
    }
    @GetMapping("{currentPage}/{pageSize}")
    public IPage<Book> getPage(@PathVariable int currentPage ,@PathVariable int pageSize   ){
        return bookService.getPage(currentPage,pageSize);
    }
}

在这里插入图片描述

2、表现层消息一致性处理

  • 设计表现层返回结果的模型类,用于后端与前端进行数据格式统一,也称为前后端数据协议
@Data
public class R {
    private Boolean flag;
    private Object data;
    public R(){}
    public R(Boolean flag){
        this.flag=flag;
    }
    public R(Boolean flag,Object data){
        this.flag=flag;
        this.data=data;
    }
}
  • 表现层接口统一返回值类型结果
@RestController
@RequestMapping("/books")
public class BookController2 {
    @Autowired
    private IBookService bookService;
  
    @PostMapping
    public R save(Book book){
      Boolean flag  =  bookService.save(book);
        return new R(flag) ;
    }
    @PutMapping
    public R update(@RequestBody Book book){
        Boolean flag = bookService.modify(book);
        return new R(flag);
    }
}

1、设计统一的返回值结果类型便于前端开发读取数据
2、返回值结果类型可以根据需求自行设定,没有固定格式
3、返回值结果类型用于后端与前端进行数据格式统一,也称为前后端数据协议

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

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

相关文章

【正点原子FPGA连载】第二十六章gpio子系统简介 摘自【正点原子】DFZU2EG_4EV MPSoC之嵌入式Linux开发指南

1&#xff09;实验平台&#xff1a;正点原子MPSoC开发板 2&#xff09;平台购买地址&#xff1a;https://detail.tmall.com/item.htm?id692450874670 3&#xff09;全套实验源码手册视频下载地址&#xff1a; http://www.openedv.com/thread-340252-1-1.html 第二十六章gpio子…

NVDLA Xilinx FPGA Mapping

Lei WangLeiWang1999要当世界第一&#xff01;78357联系我常用的链接1. 1. 硬件系统设计概述1.1. 1.1 RTL 生成1.2. 1.2 IP Package1.2.1. 1.2.1 csb2apb1.2.2. 1.2.2 关闭 Clock Gating1.2.3. 1.2.3 IP Package1.3. 1.3 Block Design1.4. 1.4 Generate Bit HDF1.5. 1.5 Sanity…

java基础一JVM之JRE、JDK、解释器、编译器详解

1.JVM、JRE和JDK区别 1.JVM&#xff08; Java Virtual Machine &#xff09;&#xff1a; Java虚拟机&#xff0c;它是整个 Java 实现跨平台的最核心的部分&#xff0c;所有的 Java 程序会首先被编译为 .class 的类文件&#xff0c;这种类文件可以在虚拟机上执行&#xff0c;…

3.10-动态规划-01背包问题

问题描述&#xff0c;给定n种物品和一个背包。物品 i 的重量是 wi &#xff0c;其价值为 vi &#xff0c;背包的容量为 c &#xff0c;问应该如何选择装入背包中的物品&#xff0c;使得装入背包的物品总价值最大&#xff1f; 写在前面 dp数组的含义--dp[i][j]表述容量为j 已经…

【计算机体系结构-03】ISA (Instruction Set Architecture) 指令集架构特性

1. 指令的类型 上一篇文章里主要介绍了几种机器模型&#xff0c;有机器模型后需要知道计算机有什么样的基本指令&#xff0c;接下来就来看看指令都有哪些类型。 [注]&#xff1a;以下指令主要为 MIPS 指令。 类型指令数据传输LD、ST、MFC1、MTC1、MFC0、MTC0计算ADD、SUB、AN…

Vue3和Vue2的slot-scope插槽用法

目录 &#x1f9e8;&#x1f9e8;&#x1f9e8;第一种插槽&#xff08;匿名插槽&#xff09; &#x1f9e8;&#x1f9e8;&#x1f9e8;第二种插槽&#xff08;具名插槽&#xff09;以及插槽简写 具名插槽的使用 &#x1f9e8;&#x1f9e8;&#x1f9e8;第三种插槽(作用域插…

使用HTTP代理后,网速反而变慢是什么原因?

如今越来越多的人利用HTTP代理开展业务&#xff0c;但在实际使用时&#xff0c;经常会有用户发现使用了HTTP代理后&#xff0c;网速非但没有变快&#xff0c;反而还更慢了。我们今天就来说说&#xff0c;这是什么原因造成的&#xff0c;从根本入手对于我们能更有利的解决问题。…

2.Spring IOC

目录 一.如何进行注册 二、如何进行注入 三、扫描注解的原理 反射文件操作 四、什么是IOC/DI&#xff1f; 五、演示使用Spring开发的案例&#xff1a;用户管理|登陆、注册 五、常见错误总结 1、注解使用Repository 2、UserController的构造方法注入&#xff1a; 3、…

【FreeRTOS】第一章:介绍

FreeRTOS是什么&#xff1f; Free和RTOS,Free就是免费的、自由的意思&#xff0c;RTOS 全称是 Real Time Operating System。中文名就是实时操作系统。可以看出FreeROTS 就是一个免费的 RTOS 类系统。这里要注意&#xff0c;RTOS 不是指某一个确定的系统&#xff0c;而是指一类…

联想电脑安装ubuntu18.04双系统超详细教程(23年最新教程,99%成功率)

文章目录前言电脑配置制作系统盘安装ubuntu系统更新显卡驱动安装wifi驱动完成前言 ubtuntu的长期支持版本现在应该已经出道21.04版本了&#xff0c;如果你对于版本没有要求的话&#xff0c;建议直接安装最新版ubuntu&#xff0c;因为新版的系统驱动都会进行更新&#xff0c;也…

自学 Java 怎么入门?

玩Java多年的老司机带你上车全面系统学习Java&#xff0c;并且还能教你如何学习才能在今年拿到一份不错的offer。 说到系统全面&#xff0c;就是以目前绝大部分公司招聘要求的知识内容为基准&#xff0c;毕竟我们学习Java都是为了高薪工作&#xff0c;《史记》中说”天下熙熙皆…

2.【SpringBoot源码】SpringBoot核心启动流程

目录 一、简介 二、创建SpringApplication对象 1)、推导出当前启动的项目的类型 2)、设置Initializer初始化器 3)、初始化Listener监听器 4)、反推出main方法所在的Class对象 三、运行SpringApplication#run(java.lang.String...)方法 1)、获取运行监听器 2)、发布…

unity使用对象池实现冲锋留下的残影效果

目录 效果展示 实现思路 残影代码 对象池代码 控制冲刺产生残影 CD冷却图标 效果展示 实现思路 对象池&#xff0c;有想要用的物体时可以从池子里取&#xff0c;用完再放回去。 因为在生成残影再销毁&#xff0c;这个过程中创建和销毁都需要耗费大量资源&#xff0c;因此…

shell 条件测试详解

目录 shell条件测试 一&#xff0c;条件测试的基本语法 1&#xff0c;test 2&#xff0c;[ ] 3&#xff0c;[[ ]] 二&#xff0c;文件测试表达式 1&#xff0c;判断目录是否存在&#xff1a; 2&#xff0c;判断文件file1是否有写的权限&#xff0c;结果为有 3&#xf…

重学MySQL基础(一)

文章目录重学MySQL基础&#xff08;一&#xff09;MySQL 连接管理MySQL字符编码InnoDB 记录存储结构InnoDB 表的主键生成策略&#xff1a;InnoDB 数据页结构页目录页的效验和索引事务报错记录在MySQL中创建函数时出现这种错误恶补SQL语句SQL中的条件语句SQL中的字符串函数SQL中…

python调用go语言踩坑记录

目录 基本操作 1 在go文件中加注释&#xff0c;设置为导出方法,导出C依赖 2 导出so文件&#xff08;mac或者linux下只需要so&#xff09; 3 进行调用 报错记录 踩坑1 关于结构体 2 cannot use (_Cfunc_CString)("12345") (value of type *_Ctype_char) as ty…

spring中事务失效场景

文章目录spring中事务失效场景一、权限访问问题二、方法用final修饰三、无事务嵌套有事务的方法四、没有被spring管理五、设计的表不支持事务六、没有开启事务七、错误的事务传播八、自己捕获了异常九、手动抛出别的异常十、自定义回滚异常spring中事务失效场景 一、权限访问问…

软件研发管理经验总结 - 事务管理

软件研发管理经验总结 - 事务管理 相关系列文章 软件产品研发管理经验总结-管理细分 软件研发管理经验总结 - 事务管理 目录软件研发管理经验总结 - 事务管理一、概述二、事务管理过程1、制定开发计划2、启动会议3、阅读前一天的日报4、例会/早会5、调整计划6、协调资源7、日报…

LeetCode——2325. 解密消息

一、题目 给你字符串 key 和 message &#xff0c;分别表示一个加密密钥和一段加密消息。解密 message 的步骤如下&#xff1a; 使用 key 中 26 个英文小写字母第一次出现的顺序作为替换表中的字母 顺序 。 将替换表与普通英文字母表对齐&#xff0c;形成对照表。 按照对照表…

vue全家桶(三)前端路由

vue全家桶&#xff08;三&#xff09;前端路由1.路由的概念1.1路由1.2vue Router2.vue-router的基本使用步骤2.1基本使用步骤2.2路由重定向3.vue-router的嵌套路由用法3.1嵌套路由的用法4.vue-router动态路由匹配用法5.vue-router命名路由用法6.vue-router编程式导航用法6.1 页…