Mybatis Plus案例分析

发布时间:2022-03-21 15:42:03 作者:iii
来源:亿速云 阅读:174

Mybatis Plus案例分析

引言

Mybatis Plus 是 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,简化开发、提高效率。本文将通过一个实际案例,详细分析 Mybatis Plus 的使用方法、优势以及在实际项目中的应用场景。

1. Mybatis Plus 简介

1.1 什么是 Mybatis Plus

Mybatis Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

1.2 Mybatis Plus 的特性

2. 案例背景

假设我们有一个简单的电商系统,需要管理商品信息。商品信息包括商品ID、商品名称、商品价格、商品库存等字段。我们将通过 Mybatis Plus 来实现对商品信息的增删改查操作。

3. 环境搭建

3.1 创建 Spring Boot 项目

首先,我们使用 Spring Initializr 创建一个 Spring Boot 项目,选择以下依赖:

3.2 添加 Mybatis Plus 依赖

pom.xml 中添加 Mybatis Plus 的依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3.1</version>
</dependency>

3.3 配置数据库连接

application.properties 中配置数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

4. 实体类与 Mapper 接口

4.1 创建实体类

创建一个 Product 实体类,并使用 Lombok 简化代码:

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("product")
public class Product {
    @TableId
    private Long id;
    private String name;
    private Double price;
    private Integer stock;
}

4.2 创建 Mapper 接口

创建一个 ProductMapper 接口,继承 BaseMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface ProductMapper extends BaseMapper<Product> {
}

5. Service 层与 Controller 层

5.1 创建 Service 接口

创建一个 ProductService 接口:

import com.baomidou.mybatisplus.extension.service.IService;

public interface ProductService extends IService<Product> {
}

5.2 创建 Service 实现类

创建一个 ProductServiceImpl 实现类:

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
}

5.3 创建 Controller 类

创建一个 ProductController 类,提供 RESTful 接口:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public List<Product> list() {
        return productService.list();
    }

    @PostMapping("/save")
    public boolean save(@RequestBody Product product) {
        return productService.save(product);
    }

    @PutMapping("/update")
    public boolean update(@RequestBody Product product) {
        return productService.updateById(product);
    }

    @DeleteMapping("/delete/{id}")
    public boolean delete(@PathVariable Long id) {
        return productService.removeById(id);
    }
}

6. 分页查询

Mybatis Plus 提供了内置的分页插件,我们可以轻松实现分页查询。

6.1 配置分页插件

MybatisPlusConfig 类中配置分页插件:

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

6.2 实现分页查询

ProductController 中添加分页查询接口:

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/page")
    public Page<Product> page(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        return productService.page(page);
    }
}

7. 条件查询

Mybatis Plus 提供了强大的条件查询功能,支持 Lambda 表达式,避免手写 SQL 时字段写错的问题。

7.1 实现条件查询

ProductController 中添加条件查询接口:

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/search")
    public List<Product> search(@RequestParam(required = false) String name,
                                @RequestParam(required = false) Double minPrice,
                                @RequestParam(required = false) Double maxPrice) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (name != null) {
            queryWrapper.like("name", name);
        }
        if (minPrice != null) {
            queryWrapper.ge("price", minPrice);
        }
        if (maxPrice != null) {
            queryWrapper.le("price", maxPrice);
        }
        return productService.list(queryWrapper);
    }
}

8. 事务管理

在实际项目中,事务管理是非常重要的。Mybatis Plus 与 Spring 的事务管理机制无缝集成,我们可以通过 @Transactional 注解来管理事务。

8.1 实现事务管理

ProductService 中添加一个事务管理的方法:

import org.springframework.transaction.annotation.Transactional;

public interface ProductService extends IService<Product> {

    @Transactional
    void updateStock(Long id, Integer quantity);
}

ProductServiceImpl 中实现该方法:

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Override
    @Transactional
    public void updateStock(Long id, Integer quantity) {
        Product product = getById(id);
        if (product != null) {
            product.setStock(product.getStock() - quantity);
            updateById(product);
        }
    }
}

9. 总结

通过以上案例,我们可以看到 Mybatis Plus 在简化开发、提高效率方面的强大功能。它不仅提供了强大的 CRUD 操作,还支持 Lambda 表达式、分页查询、条件查询等功能,极大地简化了开发流程。同时,Mybatis Plus 与 Spring 的事务管理机制无缝集成,使得事务管理变得更加简单。

在实际项目中,Mybatis Plus 可以帮助我们快速构建高效、稳定的数据访问层,是 MyBatis 用户的不二之选。

10. 参考资料


以上是关于 Mybatis Plus 的案例分析,希望对大家有所帮助。在实际开发中,Mybatis Plus 的强大功能可以极大地提高开发效率,减少重复代码的编写。如果你还没有尝试过 Mybatis Plus,不妨在下一个项目中试一试,相信你会爱上它的简洁与高效。

推荐阅读:
  1. SpringBoot 整合 MyBatis-Plus 入门体验
  2. Mybatis Plus 的优点以及与 Mybatis的区别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis plus

上一篇:Redis监控工具RedisInsight怎么安装与使用

下一篇:Android怎么实现手机联系人分栏效果

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》