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方案的更多相关文章

  1. springboot整合mybatis,利用mybatis-genetor自动生成文件

    springboot整合mybatis,利用mybatis-genetor自动生成文件 项目结构: xx 实现思路: 1.添加依赖 <?xml version="1.0" e ...

  2. 基于eclipse的mybatis映射代码自动生成的插件

    基于eclipse的mybatis映射代码自动生成的插件 分类: JAVA 数据库 工具相关2012-04-29 00:15 2157人阅读 评论(9) 收藏 举报 eclipsegeneratori ...

  3. 基于eclipse的mybatis映射代码自动生成的插件http://blog.csdn.net/fu9958/article/details/7521681

    基于eclipse的mybatis映射代码自动生成的插件 分类: JAVA 数据库 工具相关2012-04-29 00:15 2157人阅读 评论(9) 收藏 举报 eclipsegeneratori ...

  4. Eclipse 使用mybatis generator插件自动生成代码

    Eclipse 使用mybatis generator插件自动生成代码 标签: mybatis 2016-12-07 15:10 5247人阅读 评论(0) 收藏 举报 .embody{ paddin ...

  5. solr亿万级索引优化实践-自动生成UUID

    solr亿万级索引优化实践(三) 原创 2017年03月14日 17:03:09        本篇文章主要介绍下如何从客户端solrJ以及服务端参数配置的角度来提升索引速度. solrJ6.0提供的 ...

  6. JAVA入门[7]-Mybatis generator(MBG)自动生成mybatis代码

    一.新建测试项目 新建Maven项目MybatisDemo2,修改pom.xml引入依赖.dependencies在上节基础上新增 <dependency> <groupId> ...

  7. Spring Boot MyBatis 通用Mapper 自动生成代码

    一.在pom.xml文件中进入mybatis自动生成代码相关的jar包: 注意: <configurationFile>标签中配置的是“generatorConfig.xml”文件位置. ...

  8. 【Mybatis】MyBatis之Generator自动生成代码(九)

    MyBatis Generator 简介 MyBatis Generator 连接数据库表并生成MyBatis或iBatis文件.这有助于最大限度地减少使用MyBatis时为数据库文件创建简单CRUD ...

  9. mybatis添加信息自动生成主键

    一.使用Oracle数据库 举例:添加员工的时候自动生成主键 1.在dao接口中声明方法 2.在mapper中实现该方法 需要先在数据表中创建序列 3.测试 注意:在调用过save方法之后,emp对象 ...

随机推荐

  1. bzoj 1951 [Sdoi2010]古代猪文 ——数学综合

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1951 数学综合题. 费马小定理得指数可以%999911658,又发现这个数可以质因数分解.所 ...

  2. Java实现Queue类

    Java实现Queue类 import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Sc ...

  3. 设置eclipse中jsp/html文件好看的自动排版

    注:本文转载于ieayoio,原文链接:https://blog.csdn.net/ieayoio/article/details/49930587#8912689 eclipse中jsp文件代码的排 ...

  4. jenkins jacoco

    1.pom中加jacoco依赖 <dependency> <groupId>org.jacoco</groupId> <artifactId>jacoc ...

  5. laravel 对于ajax请求返回的数据

    ajax在调试器中的位置  XHR 代表 XMlHTTPREQUET 一般ajax请求php的时候我们需要给返回什么数据呢? 一般我都是直接renturn 数组的 其实也没啥问题 但是还是感觉第三种写 ...

  6. Hot resize Multipath Disk – Linux

    This post is for the users of the great dm-multipath system in Linux, who encounter a major availabi ...

  7. H264码流结构分析和rtp打包结构详解

    网络抽象层单元类型 (NALU): NALU头由一个字节组成,它的语法如下: +---------------+      |0|1|2|3|4|5|6|7|      +-+-+-+-+-+-+-+ ...

  8. 2015.4.25利用UIAutomation 替代API函数,解决了ListView无法读数据的难题,顺便实现了鼠标模拟滚轮

    UIAutomation比API的优点是类似于消息处理机制,而不是主要靠模拟鼠标键盘发送消息 首先添加引用UIAutomationClient和UIAutomationTypes,在安装.net3.5 ...

  9. SUSE 安装mysql

    1.下载mysql rpm包 在该网站选择相应的包 http://dev.mysql.com/downloads/mysql/5.0.html 这里选择:MySQL-server-5.6.17-1.s ...

  10. mui封装的ajax请求

    由于项目中引进MUI框架,所以就不需要引进jquery,但需要和后台交互时,常写为jquery格式:所以笔者觉得有必要将mui封装的ajax请求在这里提一下: 1,mui框架基于htm5plus的XM ...