springboot + mybatis-plus架构下:
让非主键字段以注解方式自动生成32位uuid:
* 自定义注解如下 @Documented @Retention(RetentionPolicy.RUNTIME) @Target({
ElementType.FIELD, ElementType.ANNOTATION_TYPE}) public @interface GenerateUUID
{ String value() default ""; }
* 在字段上的应用方式 @GenerateUUID @TableField(fill = FieldFill.INSERT) private String
uuidCode;
其中
@TableField(fill = FieldFill.INSERT)
为mybatis-plus中设置的引用方法。引用方法设置如下:
3. 实现MetaObjectHandler接口,如上注解为insert则走insertFill方法
@Component public class MyMetaObjectHandler implements MetaObjectHandler {
@Override public void insertFill(MetaObject metaObject) { Object originalObject
= metaObject.getOriginalObject(); try{ Class clazz = originalObject.getClass();
for (Field declaredField : clazz.getDeclaredFields()) { declaredField.
setAccessible(true); if (declaredField.isAnnotationPresent(GenerateUUID.class)
&& declaredField.get(originalObject) == null){ this.setFieldValByName(
declaredField.getName(),IdWorker.get32UUID(),metaObject); } } } catch (
IllegalAccessException e) { e.printStackTrace(); } } @Override public void
updateFill(MetaObject metaObject) { } }