mybatis新增物件自動生成uuid方案

bangiao發表於2018-12-31

mybatis新增物件時, 使用攔截器自動生成uuid方案
有了它不再去xml中手動新增selectKey了, 生成id方案實現類自行實現, 實現IdGenerator介面便可, 主要程式碼由公司同事編寫, 我進行改造

使用時可以在id欄位上新增@Id註解, 也可以在getId方法上新增或者不新增, 但是主鍵名字必須是id, 型別必須是String

@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface Id {

	Class<?> strategy() default UUIDGenerator.class;
}

  

public interface IdGenerator {

    Serializable generator();
}

  

public class PropertySet {

	private Set<ProPertyStrategyMapper> propertys = new HashSet<ProPertyStrategyMapper>();

	private Class<?> entity;

	@SuppressWarnings("unused")
	private PropertySet() {

	}

	public PropertySet(Class<?> entity) {
		this.entity = entity;
		this.build();
	}

	public Set<ProPertyStrategyMapper> getPropertys() {
		return propertys;
	}

	public void setPropertys(Set<ProPertyStrategyMapper> propertys) {
		this.propertys = propertys;
	}

	public PropertySet build() {
        List<Field> fieldList = new ArrayList<>();
        Class clazz = entity;
        while (null != clazz) {
            Field[] declaredFields = clazz.getDeclaredFields();
            fieldList.addAll(Arrays.asList(declaredFields));
            clazz = clazz.getSuperclass();
        }
		for (Field field : fieldList) {
			if ("serialVersionUID".equals(field.getName()))
                continue;
            field.setAccessible(true);
			PropertyDescriptor propertyDescriptor = null;
			try {
				propertyDescriptor = new PropertyDescriptor(field.getName(), entity);
			} catch (IntrospectionException e) {
				e.printStackTrace();
			}
			if (propertyDescriptor == null)
				continue;
			// 獲取類的get方法
			Method method = propertyDescriptor.getReadMethod();
			if (method == null) {
				continue;
			}
            if (field.isAnnotationPresent(Id.class)) {
                Id id = field.getAnnotation(Id.class);
                if (null == id.strategy()) {
                    continue;
                }
                Class<?> strategy = id.strategy();
                Object newInstance = null;
                try {
                    newInstance = strategy.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (!(newInstance instanceof IdGenerator)) {
                    continue;
                }
                IdGenerator idGenerator = (IdGenerator) newInstance;
                ProPertyStrategyMapper proPertyStrategyMapper = new ProPertyStrategyMapper(field.getName(),
                        idGenerator);
                propertys.add(proPertyStrategyMapper);
            }
			else if (method.isAnnotationPresent(Id.class)) {
				Id id = method.getAnnotation(Id.class);
				if (id.strategy() == null) {
					continue;
				}
				Class<?> generator = id.strategy();
				Object object = null;
				try {
					object = generator.newInstance();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				if (!(object instanceof IdGenerator)) {
					continue;
				}
				IdGenerator idGenerator = (IdGenerator) object;
				ProPertyStrategyMapper proPertyStrategyMapper = new ProPertyStrategyMapper(field.getName(),
						idGenerator);
				propertys.add(proPertyStrategyMapper);
				break;
			} else if (String.class.equals(field.getType()) && "id".equalsIgnoreCase(field.getName())) {
                IdGenerator idGenerator = new UUIDGenerator();
                ProPertyStrategyMapper proPertyStrategyMapper = new ProPertyStrategyMapper(field.getName(),
                        idGenerator);
                propertys.add(proPertyStrategyMapper);
            }
		}
		return this;
	}
}

  

public class ProPertyStrategyMapper {

	private String propertyName;
	private IdGenerator generator;

	public ProPertyStrategyMapper(String propertyName, IdGenerator generator) {
		super();
		this.propertyName = propertyName;
		this.setGenerator(generator);
	}

	public String getPropertyName() {
		return propertyName;
	}

	public void setPropertyName(String propertyName) {
		this.propertyName = propertyName;
	}

	public IdGenerator getGenerator() {
		return generator;
	}

	public void setGenerator(IdGenerator generator) {
		this.generator = generator;
	}

}

  

public class UUIDGenerator implements IdGenerator {

	@Override
	public Serializable generator() {
	    // 自行修改此處生成id方案
        return UUID.randomUUID().toString();
	}

}

  

@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class UUIDInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {

		Object[] args = invocation.getArgs();
		if (args == null || args.length != 2 || !(args[0] instanceof MappedStatement) || (args[1] instanceof Map)) {
			return invocation.proceed();
		}
		MappedStatement mappedStatement = (MappedStatement) args[0];
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		if (!SqlCommandType.INSERT.equals(sqlCommandType)) {
			return invocation.proceed();
		}
		setDefultProperty(args[1]);
		return invocation.proceed();
	}

	public void setDefultProperty(Object obj) {

		PropertySet propertySet = new PropertySet(obj.getClass());
		Set<ProPertyStrategyMapper> propers = propertySet.getPropertys();
		if (propers == null || propers.isEmpty())
			return;
		for (ProPertyStrategyMapper pro : propers) {
			try {
				BeanUtils.setProperty(obj, pro.getPropertyName(), pro.getGenerator().generator());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		System.out.println("init UUIDInterceptor");
	}

}

  

相關文章