package com.github.jfcloud.gene.handler; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.github.jfcloud.common.security.util.SecurityUtils; import com.github.jfcloud.gene.common.util.UserUtil; import org.apache.ibatis.reflection.MetaObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ClassUtils; import java.nio.charset.Charset; import java.util.Date; import java.util.HashMap; import java.util.Map; public class BaseEntityMetaObjectHandler implements MetaObjectHandler { private static final Logger log = LoggerFactory.getLogger(BaseEntityMetaObjectHandler.class); private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) { if (fieldVal != null) { if (metaObject.hasSetter(fieldName)) { Object userSetValue = metaObject.getValue(fieldName); String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset()); if (!StrUtil.isNotBlank(setValueStr) || isCover) { Class getterType = metaObject.getGetterType(fieldName); if (ClassUtils.isAssignableValue(getterType, fieldVal)) { metaObject.setValue(fieldName, fieldVal); } } } } } public void insertFill(MetaObject metaObject) { log.debug("mybatis plus start insert fill ...."); Map fieldsToFill = new HashMap<>(); fieldsToFill.put("createTime", new Date()); fieldsToFill.put("create_time", new Date()); fieldsToFill.put("createBy", UserUtil.getUserName()); fieldsToFill.put("delFlag", "0"); fieldsToFill.put("deleted", "0"); fieldsToFill.put("deptId", UserUtil.getDeptId()); fieldsToFill.put("groupIndex", this.getGroupIndex()); fieldsToFill.put("groupPi", this.getGroupPi()); fieldsToFill.put("tenantId", UserUtil.getTenantId()); this.fillFieldsIfExist(metaObject, fieldsToFill, false); } private void fillFieldsIfExist(MetaObject metaObject, Map fieldsToFill, boolean isCover) { for(Map.Entry entry : fieldsToFill.entrySet()) { String fieldName = entry.getKey(); Object defaultValue = entry.getValue(); if (metaObject.hasGetter(fieldName)) { fillValIfNullByName(fieldName, defaultValue, metaObject, isCover); } } } public void updateFill(MetaObject metaObject) { Map fieldsToFill = new HashMap<>(); fieldsToFill.put("updateTime", new Date()); fieldsToFill.put("update_time", new Date()); fieldsToFill.put("updateBy", UserUtil.getUserName()); this.fillFieldsIfExist(metaObject, fieldsToFill, false); } private Integer getGroupIndex() { return SecurityUtils.getGroupIndex(); } private Long getGroupPi() { return SecurityUtils.getGroupPi(); } }