6 Star 64 Fork 28

天乔巴夏/springboot-samples-learn

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.idea
.mvn/wrapper
spring-boot-actuator
spring-boot-aop
spring-boot-async
spring-boot-config-profile
spring-boot-docker
spring-boot-event-listener
spring-boot-exception-handler
spring-boot-freemarker
spring-boot-h2
spring-boot-jpa-restful
spring-boot-jpa
spring-boot-kafka
spring-boot-logback
spring-boot-mybatis-plus-primer
sql
src
README.md
pom.xml
spring-boot-mybatis-plus
spring-boot-quartz
spring-boot-shiro
spring-boot-slimming
spring-boot-swagger-ui
spring-boot-task
spring-boot-thymeleaf
spring-boot-validator-form
srping-boot-upload-download
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

逻辑删除功能

博客地址:MybatisPlus的逻辑删除功能使用!

自动填充

  • 在指定字段标注注解,生成器策略部分也可以配置。
    // 创建时间
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    // 更新时间
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
public enum FieldFill {
    /**
     * 默认不处理
     */
    DEFAULT,
    /**
     * 插入填充字段
     */
    INSERT,
    /**
     * 更新填充字段
     */
    UPDATE,
    /**
     * 插入和更新填充字段
     */
    INSERT_UPDATE
}
  • 实现元对象处理接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // fieldName 指的是实体类的属性名,而不是数据库的字段名
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(
            metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(
            metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(
            // 起始版本 3.3.0(推荐)
            metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 或者
        this.strictUpdateFill(
            // 起始版本 3.3.3(推荐)
            metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); 
    }
}

乐观锁插件

乐观锁适用于读多写少的场景。

乐观锁的实现机制:

  1. 取出记录时,获取当前version
  2. 更新时,带上这个version
  3. 执行更新时, set version = newVersion where version = oldVersion
  4. 如果version不对,就更新失败

使用方法:

  • 在字段上加上@Version注解。
    // 版本号
    @Version
    private Integer version;
  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity
  • 仅支持 updateById(id)update(entity, wrapper) 方法
  • update(entity, wrapper) 方法下, wrapper 不能复用!!!
  • 配置乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
  • 测试,为更新的实体设置期望的版本号:
    @Test
    void update() {
        //PDATE user SET name=?, update_time=?, version=? WHERE id=? 
        // AND version=? AND deleted=0
        int version = 2;
        User user = new User();
        user.setId(1320037517763842049L);
        user.setName("sm2");
        user.setVersion(version);//期望的版本号
        boolean b = userService.updateById(user);
        System.out.println(b);
    }

六、SQL分析打印

地址: 执行 SQL 分析打印,该插件有性能损耗,不建议生产环境使用。

  1. 引入maven依赖
<dependency>
  <groupId>p6spy</groupId>
  <artifactId>p6spy</artifactId>
  <version>最新版本</version>
</dependency>
  1. 配置application.yml
spring:
  datasource:
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver #p6spy 提供的驱动类
    url: jdbc:p6spy:mysql://localhost:3306/eblog?serverTimezone=GMT%2B8 #url 前缀为 jdbc:p6spy
    ...
  1. 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

如何在控制台打印sql语句的执行结果?

<==    Columns: id, content, authorAvatar
<==        Row: 2, <<BLOB>>, /res/images/avatar/0.jpg
<==        Row: 1, <<BLOB>>, /res/images/avatar/default.png
<==      Total: 2

配置mybatis-plus.configuration.log-implorg.apache.ibatis.logging.stdout.StdOutImpl

多租户的使用

核心插件: TenantLineInnerInterceptor

核心处理器:TenantLineHandler

public interface TenantLineHandler {

    /**
     * 获取租户 ID 值表达式,只支持单个 ID 值
     * <p>
     *
     * @return 租户 ID 值表达式
     */
    Expression getTenantId();

    /**
     * 获取租户字段名
     * <p>
     * 默认字段名叫: tenant_id
     *
     * @return 租户字段名
     */
    default String getTenantIdColumn() {
        return "tenant_id";
    }

    /**
     * 根据表名判断是否忽略拼接多租户条件
     * <p>
     * 默认都要进行解析并拼接多租户条件
     *
     * @param tableName 表名
     * @return 是否忽略, true:表示忽略,false:需要解析并拼接多租户条件
     */
    default boolean ignoreTable(String tableName) {
        return false;
    }
}

说明:

多租户 != 权限过滤,不要乱用,租户之间是完全隔离的!!! 启用多租户后所有执行的method的sql都会进行处理. 自写的sql请按规范书写(sql涉及到多个表的每个表都要给别名,特别是 inner join 的要写标准的 inner join)

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
    // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
    //        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());

    interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(
        new TenantLineHandler() {
            // manager_id = 1088248166370832385

            // 获取租户 ID 值表达式,只支持单个 ID 值
            @Override
            public Expression getTenantId() {
                return new LongValue(1088248166370832385L);
            }
            // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件,
            // 这里设置 role表不需要该条件
            @Override
            public boolean ignoreTable(String tableName) {
                if ("role".equals(tableName)) {
                    return true;
                }
                return false;
            }

            @Override
            public String getTenantIdColumn() {
                return "manager_id";
            }
        }));
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
}

@Bean
public ConfigurationCustomizer configurationCustomizer() {
    return configuration -> configuration.setUseDeprecatedExecutor(false);
}

动态表名

添加配置 DynamicTableNameInnerInterceptor

@Configuration
@MapperScan("com.baomidou.mybatisplus.samples.dytablename.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
            put("user", (sql, tableName) -> {
                String year = "_2018";
                int random = new Random().nextInt(10);
                if (random % 2 == 1) {
                    year = "_2019";
                }
                return tableName + year;
            });
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        return interceptor;
    }
}

测试随机访问user_2018和user_2019

@SpringBootTest
class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    void test() {
        // 自己去观察打印 SQL 目前随机访问 user_2018  user_2019 表
        for (int i = 0; i < 6; i++) {
            User user = userMapper.selectById(1);
            System.err.println(user.getName());
        }
    }
}

sql注入器

基本使用

  1. 创建方法的类,继承AbstractMethod。
/**
 *
 * 删除全部
 * @author Summerday
 */
public class DeleteAll extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {

        // 执行sql,动态sql参考类SqlMethod
        String sql = "delete from " + tableInfo.getTableName();
        // mapper方法接口名一致
        String method = "deleteAll";

        SqlSource sqlSource = 
            languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addDeleteMappedStatement(mapperClass,method,sqlSource);
    }
}
  1. 创建注入器,既可以继承DefaultSqlInjector,也可以实现ISqlInjector接口。
/**
 * 自定义sql注入
 * @author Summerday
 */
@Component
public class MySqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {

        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        //增加自定义方法
        methodList.add(new DeleteAll());
        methodList.add(new FindOne());

        /*
         * 以下 3 个为内置选装件
         * 头 2 个支持字段筛选函数
         */
        // 例: 不要指定了 update 填充的字段
        methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
        methodList.add(new AlwaysUpdateSomeColumnById());
        methodList.add(new LogicDeleteByIdWithFill());
        return methodList;
    }
}
  1. 如果想要所有的mapper都拥有自定义的方法,可以自定义接口继承BaseMapper接口,我们的业务接口就可以继承自定义的baseMapper接口了。
/**
 * 自定义baseMapper接口
 * @author Summerday
 */
public interface MyBaseMapper<T> extends BaseMapper<T> {

    //自定义方法,删除所有,返回影响行数
    int deleteAll();

    // 根据id找到
    T findOne(Serializable id);
}

@Mapper
public interface UserMapper extends MyBaseMapper<User> {
}
  1. 测试接口
@RunWith(SpringRunner.class)
@SpringBootTest
class InjectTest {

    @Resource
    UserMapper userMapper;

    @Test
    void inject(){
        int rows = userMapper.deleteAll();
        System.out.println(rows);
    }

    @Test
    void findOne(){
        User one = userMapper.findOne(1L);
        System.out.println(one);
    }
}

选装件

  1. InsertBatchSomeColumn:批量新增数据,自选字段insert

  2. LogicDeleteByIdWithFill:根据id逻辑删除数据,并带字段填充功能

  3. AlwaysUpdateSomeColumnById:根据 ID 更新固定的那几个字段但是不包含逻辑删除)

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/tqbx/springboot-samples-learn.git
git@gitee.com:tqbx/springboot-samples-learn.git
tqbx
springboot-samples-learn
springboot-samples-learn
master

搜索帮助