使用mybatisplus自带的字段填充策略注入值的时候,发现并没有扫描到我的指定字段。
1. 初始代码
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {private static final String createByFiled = "createBy";private static final String updateByFiled = "updateBy";@Overridepublic void updateFill(MetaObject metaObject) {Object originalObject = metaObject.getOriginalObject();// 有这个属性 才执行if (metaObject.hasSetter("updateTime") ) {this.setUpdateFieldValByName( "updateTime", LocalDateTime.now(),metaObject);}boolean b = metaObject.hasGetter("updateBy");// 返回的是falseObject fieldValByName = getFieldValByName(updateByFiled, metaObject);if (b && fieldValByName == null){// 有这个属性 并且这个字段的属性为空 才执行this.setInsertFieldValByName(updateByFiled, value222, metaObject);}boolean hasField = this.hasField(metaObject, "update1234");//falseboolean hasField1 = this.hasField(metaObject, "updateBy");// true}/*** <p>@Description: 摘抄自 MetaObjectHandler.setFieldValByName() 方法</p >* <p>@param [metaObject, fieldName]</p >* <p>@return boolean</p >* <p>@throws </p >* <p>@date 2024/6/21 13:29</p >*/private boolean hasField(MetaObject metaObject, String fieldName) {if (metaObject.hasSetter(fieldName) && metaObject.hasGetter(fieldName)) {
// metaObject.setValue(fieldName, fieldVal);return true;} else if (metaObject.hasGetter(Constants.ENTITY)) {Object et = metaObject.getValue(Constants.ENTITY);if (et != null) {MetaObject etMeta = SystemMetaObject.forObject(et);if (etMeta.hasSetter(fieldName)) {return true;}}}return false;}}
此时发现 updateFill()方法中的metaObject.hasGetter(“updateBy”)返回的结果竟然是false
此处发现metaObject.hasGetter(“”)这个字段不靠谱,而metaObject.hasSetter()这个更不靠谱,有时候(字段不存在的情况下)直接返回true。此处决定手写判断是否存在该字段如下
2.手写判断方法,可能是mp的版本问题
/*** <p>@Description: 摘抄自 MetaObjectHandler.setFieldValByName() 方法</p >* <p>@param [metaObject, fieldName]</p >* <p>@return boolean</p >* <p>@throws </p >* <p>@date 2024/6/21 13:29</p >*/private boolean hasField(MetaObject metaObject, String fieldName) {if (metaObject.hasSetter(fieldName) && metaObject.hasGetter(fieldName)) {
// metaObject.setValue(fieldName, fieldVal);return true;} else if (metaObject.hasGetter(Constants.ENTITY)) {Object et = metaObject.getValue(Constants.ENTITY);if (et != null) {MetaObject etMeta = SystemMetaObject.forObject(et);if (etMeta.hasSetter(fieldName)) {return true;}}}return false;}