码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis新增对象自动生成uuid方案

时间:2018-12-31 11:24:38      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:ota   print   ESS   [1]   method   cep   executor   object   rri   

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");
	}

}

  

mybatis新增对象自动生成uuid方案

标签:ota   print   ESS   [1]   method   cep   executor   object   rri   

原文地址:https://www.cnblogs.com/bangiao/p/10201449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!