package com.nanxiislet.admin.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.apache.ibatis.reflection.MetaObject; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.time.LocalDateTime; /** * MyBatis-Plus 配置 * * @author NanxiIslet * @since 2024-01-06 */ @Configuration public class MybatisPlusConfig { /** * MyBatis-Plus 插件配置 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 分页插件 PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL); paginationInterceptor.setMaxLimit(500L); paginationInterceptor.setOverflow(true); interceptor.addInnerInterceptor(paginationInterceptor); // 乐观锁插件 interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 防止全表更新删除插件 interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); return interceptor; } /** * 自动填充处理器 */ @Component public static class AutoFillMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { LocalDateTime now = LocalDateTime.now(); this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, now); this.strictInsertFill(metaObject, "updatedAt", LocalDateTime.class, now); this.strictInsertFill(metaObject, "deleted", Integer.class, 0); // 获取当前登录用户ID Long userId = getCurrentUserId(); if (userId != null) { this.strictInsertFill(metaObject, "createdBy", Long.class, userId); this.strictInsertFill(metaObject, "updatedBy", Long.class, userId); } } @Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now()); Long userId = getCurrentUserId(); if (userId != null) { this.strictUpdateFill(metaObject, "updatedBy", Long.class, userId); } } /** * 获取当前登录用户ID */ private Long getCurrentUserId() { try { Object loginId = cn.dev33.satoken.stp.StpUtil.getLoginIdDefaultNull(); if (loginId != null) { return Long.parseLong(loginId.toString()); } } catch (Exception ignored) { } return null; } } }