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

本文详细介绍了如何将Springboot与Junit、Mybatis、Mybatis-plus、Druid等技术进行整合,包括每个步骤、常见问题及配置。此外,还提供了数据层、业务层和表现层的整合案例,涉及基础的CRUD操作、日志配置、分页查询和条件查询等功能。
摘要由CSDN通过智能技术生成


整合第三方技术通用方式

  • 导入对应的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、返回值结果类型用于后端与前端进行数据格式统一,也称为前后端数据协议

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangkay88

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值