Mybatis提供了主键生成器接口KeyGenerator,其实现类的主键生成策略根据不同的数据库类型实现自增或者序列。
我们想使用UUID来实现自己的业务,如何实现呢?
UUID生成器
通过jvm,时间、机器ip 生成hex的32位值,具体可以参考hibernate的UUIDHexGenerator
AutoUUID 注解
通过注解,标示需要自动填充的uuid的实体类
实体类父类
统一实体类的主键,方便uuid的注入;如主键不统一,在注入的过程中可以使用,注解或者其他的方式辨识。
spring aop
通过使用spring 的aop技术来切面拦截dao层的save方法,小伙伴们的不同包名、类名、方法名可以通过aop的配置灵活运用。
代码干活
实体类父类
public abstract class BaseEntity<PK extends Serializable> implements Serializable, Cloneable { /* 实体的主键 */ public abstract PK getId(); /* 设置实体的主键值*/ public abstract void setId(PK id); }
AutoUUID 注解
@Target({ TYPE}) @Retention(RUNTIME) public @interface AutoUUID { }
拦截处理
public class GeneratedUUIDInterceptor { /** * 检测是否是BaseEntity子类,并且带有AutoUUID注解的新增方法,自动生成uuid * @param joinPoint */ public void checkUUID(JoinPoint joinPoint) { for (Object entity : joinPoint.getArgs()) { if (entity instanceof BaseEntity && entity.getClass().getAnnotation(AutoUUID.class) != null) { BaseEntity e = (BaseEntity) entity; e.setId(UIDGenerator.getInstance().createUID()); } } } }
spring aop
<bean id="generatedUUID" class="com.zohan.sdk.interceptor.myBatis.GeneratedUUIDInterceptor"/> <aop:config> <aop:aspect id="secutityAspect" ref="generatedUUID"> <aop:pointcut id="saveMethod" expression="execution(* com.zohan..dao..save*(..)) "/> <aop:before method="checkUUID" pointcut-ref="saveMethod"/> </aop:aspect> </aop:config>
示例
public class Scheduler extends BaseEntity<String> { //id private String id;