MyBatisPlusConfig.java 2.11 KB
package vion.config.mp;

import cn.dev33.satoken.stp.StpUtil;
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.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import vion.vo.UserVO;

import java.time.LocalDateTime;

/**
 * @author vion
 * @date 2022/7/20
 */
@Configuration
public class MyBatisPlusConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.fillHasGetter(metaObject, "createTime", LocalDateTime.now());
        this.fillHasGetter(metaObject, "modifyTime", LocalDateTime.now());
        this.fillHasGetter(metaObject, "updateTime", LocalDateTime.now());
        try {
            // 获取当前登录用户,并填充
            var vo = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
            this.fillHasGetter(metaObject, "creator", vo.getUserid());
        } catch (Exception ignored) {
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.fillHasGetter(metaObject, "modifyTime", LocalDateTime.now());
        this.fillHasGetter(metaObject, "updateTime", LocalDateTime.now());
        try {
            var vo = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
            this.fillHasGetter(metaObject, "updater", vo.getUserid());
        } catch (Exception ignored) {
        }
    }

    protected void fillHasGetter(MetaObject metaObject, String fieldName, Object fieldVal) {
        if (metaObject.hasGetter(fieldName)) {
            this.fillStrategy(metaObject, fieldName, fieldVal);
        }
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        return interceptor;
    }

}