java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > MyBatis-Plus插件通用Service

MyBatis-Plus插件机制及通用Service新功能

作者:陶然同学

这篇文章主要介绍了MyBatis-Plus插件机制以及通用Service、新功能,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1.高级(插件机制)

1.1自动填充

项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间等。

我们可以使用MyBatis Plus的自动填充功能,完成这些字段的赋值工作:

1.1.1 原理

1.1.2 基本操作

步骤一:修改表添加字段

alter table tmp_customer add column create_time date;
alter table tmp_customer add column update_time date;

步骤二:修改JavaBean

package com.czxy.mp.domain;
 
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
 
import java.util.Date;
 
/**
 * Created by liangtong.
 */
@Data
@TableName("tmp_customer")
public class Customer {
    @TableId(type = IdType.AUTO)
    private Integer cid;
    private String cname;
    private String password;
    private String telephone;
    private String money;
 
    @TableField(value="create_time",fill = FieldFill.INSERT)
    private Date createTime;
 
    @TableField(value="update_time",fill = FieldFill.UPDATE)
    private Date updateTime;
 
}

步骤三:编写处理类

package com.czxy.mp.handler;
 
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
 
import java.util.Date;
 
 
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
    }
 
    /**
     * 更新填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

步骤四:测试

 @Test
    public void testInsert() {
        Customer customer = new Customer();
        customer.setCname("测试888");
 
        customerMapper.insert(customer);
    }
 
    @Test
    public void testUpdate() {
        Customer customer = new Customer();
        customer.setCid(11);
        customer.setTelephone("999");
 
        customerMapper.updateById(customer);
    }

1.2乐观锁

1.2.1 什么是乐观锁

取出记录时,获取当前version

更新时,带上这个version

执行更新时, set version = newVersion where version = oldVersion

如果version不对,就更新失败

1.2.2. 实现

步骤:

package com.czxy.mp.domain;
 
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
 
/**
 * Created by liangtong.
 */
@Data
@TableName("tmp_customer")
public class Customer {
    @TableId(type = IdType.AUTO)
    private Integer cid;
    private String cname;
    private String password;
    private String telephone;
    private String money;
    @Version
    @TableField(fill = FieldFill.INSERT)
    private Integer version;
}

package com.czxy.mp.config;
 
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
 
import java.util.Date;
 
/**
 * Created by liangtong.
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("version", 1, metaObject);
    }
 
    /**
     * 更新填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

步骤四:修改 MybatisPlusConfig 开启乐观锁

package com.czxy.mp.config;
 
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * Created by liangtong.
 */
@Configuration
public class MybatisPlusConfig {
     */
    /**
     * 配置插件
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
 
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
 
        return mybatisPlusInterceptor;
    }
}
 @Test
    public void testUpdate() {
        Customer customer = new Customer();
        customer.setCid(14);
        customer.setCname("测试999");
        // 与数据库中数据一致,将更新成功,否则返回失败。
        customer.setVersion(1);
 
        int i = customerMapper.updateById(customer);
        System.out.println(i);
    }

1.2.3 注意事项

支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime

整数类型下 newVersion = oldVersion + 1

newVersion 会回写到 entity

仅支持 updateById(id)update(entity, wrapper) 方法

update(entity, wrapper) 方法下, wrapper 不能复用!!!

数据库表的version字段,必须有默认值(SQL语句默认值、或MyBatisPlus自动填充)

在进行更新操作时,必须设置version值,否则无效。

1.3逻辑删除

1.3.1 什么是逻辑删除

逻辑删除,也称为假删除。就是在表中提供一个字段用于记录是否删除,实际该数据没有被删除。

1.3.2 实现

步骤:

步骤一:环境(表提供字段deleted、JavaBean属性 deleted、填充默认值0)

步骤二:修改JavaBean,添加注解 @TableLogic

步骤一:修改表结构添加deleted字段

步骤二:修改JavaBean,给deleted字段添加@TableLogic

package com.czxy.mp.domain;
 
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
 
/**
 * Created by liangtong.
 */
@Data
@TableName("tmp_customer")
public class Customer {
    @TableId(type = IdType.AUTO)
    private Integer cid;
    private String cname;
    private String password;
    private String telephone;
    private String money;
    @Version
    @TableField(fill = FieldFill.INSERT)
    private Integer version;
 
    @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private Integer deleted;
}

步骤三:添加数据时,设置默认“逻辑未删除值”

package com.czxy.mp.config;
 
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
 
import java.util.Date;
 
/**
 * Created by liangtong.
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("version", 1, metaObject);
        this.setFieldValByName("deleted", 0, metaObject);
    }
 
    /**
     * 更新填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

步骤四:测试

  @Test
    public void testDelete() {
        // 删除时,必须保证deleted数据为“逻辑未删除值”
        int i = customerMapper.deleteById(12);
        System.out.println(i);
    }

1.3.3 注意

1.3.4 全局配置

如果使用了全局配置,可以不使用注解@TableLogic

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted  # 局逻辑删除的实体字段名
      logic-delete-value: 1  # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

1.3.5 恢复

UPDATE `tmp_customer` SET `deleted`='0' WHERE `cid`='13';

方案2:直接使用update语句,==不能==解决问题。

 @Test
    public void testUpdate() {
        Customer customer = new Customer();
        customer.setCid(13);
        customer.setDeleted(0);
        //更新
        customerMapper.updateById(customer);
    }

方案3:修改Mapper,添加 recoveryById 方法,进行数据恢复。

@Mapper
public interface CustomerMapper extends BaseMapper<Customer> {
 
    @Update("update tmp_customer set deleted = 0 where cid = #{cid}")
    public void recoveryById(@Param("cid") Integer cid);
}

2.通用Service

2.1分析 通用Service分析

2.2基本使用 标准service:接口 + 实现

service接口

package com.czxy.service;
  import com.baomidou.mybatisplus.extension.service.IService;
  import com.czxy.domain.Customer;
  public interface CustomerService extends IService<Customer> {
  }

service实现类

package com.czxy.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czxy.domain.Customer;
import com.czxy.mapper.CustomerMapper;
import com.czxy.service.CustomerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper,Customer> implements CustomerService {
 
}

2.3常见方法

package com.czxy.test;
 
import com.czxy.mp.Day62MybatisPlusApplication;
import com.czxy.mp.domain.Customer;
import com.czxy.mp.service.CustomerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
import javax.annotation.Resource;
import java.util.List;
 
 
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Day62MybatisPlusApplication.class)
public class TestDay62CustomerService {
 
    @Resource
    private CustomerService customerService;
 
    @Test
    public void testSelectList() {
        List<Customer> list = customerService.list();
        list.forEach(System.out::println);
    }
 
    @Test
    public void testInsert() {
        Customer customer = new Customer();
        customer.setCname("张三");
        customer.setPassword("9999");
        // 添加
        customerService.save(customer);
    }
 
    @Test
    public void testUpdate() {
        Customer customer = new Customer();
        customer.setCid(14);
        customer.setCname("777");
        customer.setPassword("777");
 
        customerService.updateById(customer);
    }
 
    @Test
    public void testSaveOrUpdate() {
        Customer customer = new Customer();
        customer.setCid(15);
        customer.setCname("999");
        customer.setPassword("99");
 
        customerService.saveOrUpdate(customer);
    }
 
    @Test
    public void testDelete() {
        customerService.removeById(15);
    }
}

3.新功能

3.1执行SQL分析打印

该功能依赖 p6spy 组件,完美的输出打印 SQL 及执行时长

p6spy 依赖引入

<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

核心yml配置

spring:
  datasource:
  	# p6spy 提供的驱动代理类,
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    # url 固定前缀为 jdbc:p6spy,跟着冒号为对应数据库连接地址
    url: jdbc:p6spy:mysql://127.0.0.1:3306...

spy.properties 配置

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

3.2数据库安全保护

为了保护数据库配置及数据安全,在一定的程度上控制开发人员流动导致敏感信息泄露

步骤1-2:使用工具类生成秘钥以及对敏感信息进行加密

package com.czxy;
import com.baomidou.mybatisplus.core.toolkit.AES;
import org.junit.Test;
public class TestAES {
    @Test
    public void testAes() {
        String randomKey = AES.generateRandomKey();
 
        String url =  "jdbc:p6spy:mysql://127.0.0.1:3306/zx_edu_teacher?useUnicode=true&characterEncoding=utf8";
        String username = "root";
        String password = "1234";
 
        String urlAES = AES.encrypt(url, randomKey);
        String usernameAES = AES.encrypt(username, randomKey);
        String passwordAES = AES.encrypt(password, randomKey);
 
        System.out.println("--mpw.key=" + randomKey);
        System.out.println("mpw:" + urlAES);
        System.out.println("mpw:" + usernameAES);
        System.out.println("mpw:" + passwordAES);
    }
}
// Jar 启动参数( idea 设置 Program arguments , 服务器可以设置为启动环境变量 )
//--mpw.key=fddd2b7a67460e16
//mpw:7kSEISvq3QWfnSh6vQZc2xgE+XF/sJ0WS/sgGkYpCOTQRjO1poLi3gfmGZNOwKzfqZUec0odiwAdmxcS7lfueENGIx8OmIe//d9imrGFpnkrf8jNSHdzfNPCUi3MbmUb
//mpw:qGbCMksqA90jjiGXXRr7lA==
//mpw:xKG9GABlywqar6CGPOSJKQ==

步骤3:配置加密信息

步骤4:使用秘钥启动服务

到此这篇关于MyBatis-Plus插件机制以及通用Service、新功能的文章就介绍到这了,更多相关MyBatis-Plus插件通用Service内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文