11-SpringBoot+MybatisPlus+SpringCache框架项目实战

822 阅读5分钟

上一章我们对Redis里Set集合数据结构进行个三种案例,用户画像Set集合去重实战,社交应用(关注、粉丝、共同好友)实战、SortedSet实时榜单实战。

本章我们将使用SpringBoot+MybatisPlus+SpringCache整合项目实战,首先我们得先了解什么是MybatisPlus与SpringCache。

什么是MybatisPlus?

在了解MybatisPlus之前,我们首先要了解什么是Mybatis。Mybatis是一个优秀的持久层框架,它对JDBC操作数据库的过程进行封装,以前我们使用JDBC进行连接数据库时需要编写大量的数据库注册驱动代码,这对开发者非常的不友好!降低开发者的效率。使用Mybatis后,使开发者只需要关注sql的本身,大大提高了开发效率。而MybatisPlus是Mybatis的增强工具,在MyBatis的基础上只做增强,不做改变,为的就是简化开发、提高效率(可以看出开发者对简化开发是有多强的执念啊)。

什么是SpringCache?

SpringCache是对缓存使用的抽象,通过它我们可以在不入侵业务代码的基础上让现有的代码即可支持缓存。前面说了程序要想使用缓存,就要与缓存框架进行耦合。聪明的架构师已经利用接口来减低耦合了,利用面向对象的抽象和多态的特征做到业务代码与具体框架分离。但我们仍然需要在代码中调用与缓存有关的接口和方法,在合适的时候插入数据到缓存里,在合适的时候从缓存中读取数据。

使用SpringCache有什么好处

(1)提供了类似于@Transactional注解事务的注解Cache支持

(2)提供最基本的Cache抽象,方便切换于各种底层Cache

(3)只需要更少的代码就可以完成业务数据的缓存

(4)提供事务的回滚,也会自动回滚,支持比较复杂的缓存逻辑

(5)Cache核心:一个是Cache的接口,有各种操作缓存的API

(6)一个是CacheManager管理各类缓存,有多个缓存框架的实现

使用方法:

在项目的pom.xml中引入依赖

<dependency>
 
<groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

在application.yml中添加指定缓存类型

spring:
 cache:
 type: redis

在SpringBoot中的启动类添加缓存注解@EnableCaching

@SpringBootApplication
@EnableCaching

使用MybatisPlus连接Mysql数据库

首先在项目的pom.xml文件中添加MyBatisPlus的依赖与mysql的数据库驱动

<!--mybatis plus和springboot整合-->
 <dependency>
 <groupId>com.baomidou</groupId>
 <artifactId>mybatis-plus-boot-starter</artifactId>
 <version>3.4.0</version>
 </dependency>
 
  <!--数据库驱动--> 
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>8.0.15</version>
 </dependency>  

在application.yml中添加Mysql数据库相关配置

#==============================数据库相关配置========================================
#数据库配置
 datasource:
 driver-class-name: com.mysql.cj.jdbc.Driver
 url:jdbc:mysql://127.0.0.1:3306/xdclass_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
 username: root
 password: xdclass.net
#配置plus打印sql⽇志
mybatis-plus:
 configuration:
 log-impl:org.apache.ibatis.logging.stdout.StdOutImpl

然后再在Mysql中添加运行数据库脚本,当前使用的版本为Mysql8.0

数据库和表的建立

CREATE TABLE `product` (
 `id` int(11) unsigned NOT NULL
AUTO_INCREMENT,
 `title` varchar(128) DEFAULT NULL COMMENT '标 题',
 `cover_img` varchar(128) DEFAULT NULL COMMENT'封⾯图',
 `detail` varchar(256) DEFAULT '' COMMENT '详 情',
 `amount` int(10) DEFAULT NULL COMMENT '新价格',
 `stock` int(11) DEFAULT NULL COMMENT '库存',
 `create_time` datetime DEFAULT NULL COMMENT'创建时间',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT
CHARSET=utf8mb4;

数据库与表建立好后,我们再插入数据

INSERT INTO `product` (`id`, `title`,`cover_img`, `detail`, `amount`, `stock`,`create_time`)
VALUES
 (1, '⽼王-⼩滴课堂抱枕',
'https://file.xdclass.net/video/2020/alibabacloud/zt-alibabacloud.png',
'https://file.xdclass.net/video/2021/60-MLS/summary.jpeg', 213, 100, '2021-09-12 00:00:00'),
 (2, '⽼王-技术⼈的杯⼦Linux',
'https://file.xdclass.net/video/2020/alibabacloud/zt-alibabacloud.png',
'https://file.xdclass.net/video/2021/59-Postman/summary.jpeg', 42, 100, '2021-03-12 00:00:00'),
 (3, '技术⼈的杯⼦docker',
'https://file.xdclass.net/video/2020/alibabacloud/zt-alibabacloud.png',
'https://file.xdclass.net/video/2021/60-MLS/summary.jpeg', 12, 20, '2022-09-22 00:00:00'),
 (4, '技术⼈的杯⼦git',
'https://file.xdclass.net/video/2020/alibabacloud/zt-alibabacloud.png',
'https://file.xdclass.net/video/2021/60-MLS/summary.jpeg', 14, 20, '2022-11-12 00:00:00');

当对数据插入完成后我们开始编写代码。

创建ProductDO类,@TableName就是相对应数据库的表名,@TableId是表名对应的id,id是自增。

@TableName("product")
public class ProductDO {
 @TableId(value = "id", type = IdType.AUTO)
 private Long id;
 /**
 * 标题
 */
 private String title;
 /**
 * 封⾯图
 */
 private String coverImg;
 /**
 * 详情
 */
 private String detail;
 /**
 * 新价格
 */
 private Integer amount;
 /**
 * 库存
 */
 private Integer stock;
 /**
 * 创建时间
 */
 private Date createTime;
}
//set get方法略

SpringBoot+MybatisPlus开发商品的CRUD接口

在dao层中编写Mapper

public interface ProductMapper extends BaseMapper<ProductDO> {
}

在Service层中编写ProductService

public interface ProductService {
  int save(ProductDO productDO);
  int delById(int id);
  int updateById(ProductDO productDO);
  ProductDO findById(int id);
}

在Impl层中编写接口实现类

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Override
    public int save(ProductDO productDO) {
        return productMapper.insert(productDO);
    }

    @Override
    public int delById(int id) {
        return productMapper.deleteById(id);;
    }

    @Override
    public int updateById(ProductDO productDO) {
        return productMapper.updateById(productDO);;
    }

    @Override
    public ProductDO findById(int id) {
        return productMapper.selectById(id);
    }
}

在controller层中编写controller类

@RestController
@RequestMapping("/api/vi/video")
public class ProductController {
    @Autowired
  private   ProductService productService;
    @PostMapping("add")
    public JsonData add(@RequestBody ProductDO productDO){
        productDO.setCreateTime(new Date());
        int rows = productService.save(productDO);
        return JsonData.buildSuccess(rows);
    }

    @PostMapping("update")
    public JsonData update(@RequestBody ProductDO productDO){
        productDO.setCreateTime(new Date());
        int rows = productService.updateById(productDO);
        return JsonData.buildSuccess(rows);
    }

    @DeleteMapping("del")
    public JsonData del(int id){
        int rows = productService.delById(id);
        return JsonData.buildSuccess(rows);

    }
   @GetMapping("find")
    public JsonData finById(int id){
        ProductDO productDO = productService.findById(id);
        return JsonData.buildSuccess(productDO);

    }

}

使用Postman进行测试,返回有数据代表成功。

接下来使用MybatisPlus开发分页接口,如何使用分页加入到缓存中。

首先在Service层中添加分页接口

Map<String,Object> page(int page, int size);

再去接口实现类中编写代码

@Override
 public Map<String, Object> page(int page,int size) {
 Page<ProductDO> pageInfo = new Page<>(page, size);
 IPage<ProductDO> productDOIPage = productMapper.selectPage(pageInfo, null);
 Map<String, Object> pageMap = new HashMap<>(3);
 pageMap.put("total_record", productDOIPage.getTotal());
 pageMap.put("total_page", productDOIPage.getPages());
 pageMap.put("current_data", productDOIPage.getRecords());
 return pageMap;
 }

在controller层中的ProductController编写代码

@GetMapping("page")
public JsonData page(int page, int size){
Map<String,Object> map = productService.page(page,size);
    return JsonData.buildSuccess(map);
}

在config工具类中添加分页插件

/**
 * 新的分⻚插件
 */
 @Bean
 public MybatisPlusInterceptor mybatisPlusInterceptor() {
 MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
 return interceptor;
 }

上面代码编写完后,我们使用Postman对分页数据进行测试,可以看到page=1是第一页,size=3为每一页显示多数数据。

到这里就已经把整个项目整合完毕了,后面会介绍如何使用SpringCache对数据进行缓存,来提高效率。


本章小结: 本章主要是使用Boot+MybatisPlus+SpringCache整合了一个CRUD的项目,使用MybatisPlus能够大大的简化了编写SQL语句的时间,而SpringCache就是把方法返回的数据保存到缓存中,后面的章节会有介绍。完成这个项目的整合后,接下来的课程就是基于这个项目的基础上开始学习了。