mybatis新增对象自动生成uuid方案
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方案的更多相关文章
- springboot整合mybatis,利用mybatis-genetor自动生成文件
springboot整合mybatis,利用mybatis-genetor自动生成文件 项目结构: xx 实现思路: 1.添加依赖 <?xml version="1.0" e ...
- 基于eclipse的mybatis映射代码自动生成的插件
基于eclipse的mybatis映射代码自动生成的插件 分类: JAVA 数据库 工具相关2012-04-29 00:15 2157人阅读 评论(9) 收藏 举报 eclipsegeneratori ...
- 基于eclipse的mybatis映射代码自动生成的插件http://blog.csdn.net/fu9958/article/details/7521681
基于eclipse的mybatis映射代码自动生成的插件 分类: JAVA 数据库 工具相关2012-04-29 00:15 2157人阅读 评论(9) 收藏 举报 eclipsegeneratori ...
- Eclipse 使用mybatis generator插件自动生成代码
Eclipse 使用mybatis generator插件自动生成代码 标签: mybatis 2016-12-07 15:10 5247人阅读 评论(0) 收藏 举报 .embody{ paddin ...
- solr亿万级索引优化实践-自动生成UUID
solr亿万级索引优化实践(三) 原创 2017年03月14日 17:03:09 本篇文章主要介绍下如何从客户端solrJ以及服务端参数配置的角度来提升索引速度. solrJ6.0提供的 ...
- JAVA入门[7]-Mybatis generator(MBG)自动生成mybatis代码
一.新建测试项目 新建Maven项目MybatisDemo2,修改pom.xml引入依赖.dependencies在上节基础上新增 <dependency> <groupId> ...
- Spring Boot MyBatis 通用Mapper 自动生成代码
一.在pom.xml文件中进入mybatis自动生成代码相关的jar包: 注意: <configurationFile>标签中配置的是“generatorConfig.xml”文件位置. ...
- 【Mybatis】MyBatis之Generator自动生成代码(九)
MyBatis Generator 简介 MyBatis Generator 连接数据库表并生成MyBatis或iBatis文件.这有助于最大限度地减少使用MyBatis时为数据库文件创建简单CRUD ...
- mybatis添加信息自动生成主键
一.使用Oracle数据库 举例:添加员工的时候自动生成主键 1.在dao接口中声明方法 2.在mapper中实现该方法 需要先在数据表中创建序列 3.测试 注意:在调用过save方法之后,emp对象 ...
随机推荐
- compile cef2526
fetch --nohooks chromium cd /path/to/chromium/src# git checkout -b 51.0.2704.103 refs/tags/51.0.2704 ...
- 机器学习:评价分类结果(F1 Score)
一.基础 疑问1:具体使用算法时,怎么通过精准率和召回率判断算法优劣? 根据具体使用场景而定: 例1:股票预测,未来该股票是升还是降?业务要求更精准的找到能够上升的股票:此情况下,模型精准率越高越优. ...
- Java-API:java.util.UUID
ylbtech-Java-API:java.util.UUID 1.返回顶部 2.返回顶部 3.返回顶部 4. 百科返回顶部 5.返回顶部 0. https://docs.oracle ...
- Python多进程-进程间数据的传递
两个进程间的数据是独立的,要进行数据传递的话可通过几个方法 Queue 通过队列来进行进程间数据的传递 # -*- coding:utf-8 -*- __author__ = "MuT6 S ...
- Laravel 在 with 查询中只查询个别字段
在使用 Laravel 的关联查询中,我们经常使用 with 方法来避免 N+1 查询,但是 with 会将目标关联的所有字段全部查询出来,对于有强迫症的我们来说,当然是不允许的. 这时候我们可以使用 ...
- python paramiko 调试
#!/usr/bin/env python #-*- encoding:utf-8 -*- import paramiko transport = paramiko.Transport(('10.34 ...
- 管理linked break-off snapshot
1. 建立linked break-off snapshot (1) 建立原卷 #> vxassist -g APS2_AFC_DG make vol1 4096000 #> vxpr ...
- Firemonkey Android IOS 图标
图标很多
- 最全SDWebImage-3.8版本源码阅读详解
一.前言 SDWebImage,非常友好的网络图片加载第三方框架,在GitHub中已经获得了15000++的star,链接地址:https://github.com/rs/SDWebImage 本人分 ...
- ffmpeg: ‘UINT64_C’ was not declared in this scope (转)
ffmpeg 默认是用C文件来编译的,如果某个CPP文件想引用ffmpeg中的某些函数或者头文件,有可能出现 ‘UINT64_C’ was not declared in this scope的错误 ...