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