SpringBoot2.X+MybatisPlus+SpringCache框架项目实战

一 SpringCache简介

  • 文档:https://spring.io/guides/gs/caching/

  • 自Spring 3.1起,提供了类似于@Transactional注解事务的注解Cache支持,且提供了Cache抽象

  • 提供基本的Cache抽象,方便切换各种底层Cache

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

  • 提供事务回滚时也自动回滚缓存,支持比较复杂的缓存逻辑

  • 核心

    • 一个是Cache接口,缓存操作的API;
    • 一个是CacheManager管理各类缓存,有多个缓存框架的实现

二 使用

  • 项目中引入starter
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
  • 配置文件指定缓存类型
    spring:
      cache:
        type: redis
  • 启动类开启缓存注解
    @EnableCaching

三 整合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>

  • 新增配置
    #==============================数据库相关配置========================================
    #数据库配置
      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

  • 数据库和表建立
    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');
    ​
  • DO类编写
    @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;
    ​
    }
  • 编写Mapper
    public interface ProductMapper extends BaseMapper<ProductDO> {
    }
  • 编写Service
    @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
    @RestController
    @RequestMapping("/api/v1/video")
    public class ProductController {
    
    
        @Autowired
        private ProductService productService;
    
    
        /**
         * 新增
         * @param productDO
         * @return
         */
        @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){
    
            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 findById(int id){
    
            ProductDO productDO  = productService.findById(id);
            return JsonData.buildSuccess(productDO);
        }
    
    }

    四  MybatisPlus分页接口
     

    @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;
        }
  • 分页插件配置
    /**
         * 新的分页插件
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值