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对象 ...
随机推荐
- iOS 【资源篇】
iOS9开发入门教程索引 Objective-C视频教程 O-c Blog 社区 畅游 http://www.9ria.com/ 苹果中文开发社区 http://www.cocoachina.co ...
- 西安电子科技大学第16届程序设计竞赛 G-小国的复仇
西安电子科技大学第16届程序设计竞赛网络同步赛 G-小国的复仇 2 链接:https://www.nowcoder.com/acm/contest/107/G来源:牛客网 题目描述 众所周知,汀老师是 ...
- Ubuntu 下 ROS Kinetic 的安装
安装环境为 Ubuntu 16.04 配置 Ubuntu 软件仓库 打开“设置”中的“软件和更新” 把 “restricted”.“universe” 和 “multiverse” 这三项勾上 勾完后 ...
- Solaris10 如何设置空闲ssh连接超时断开
在ssh的配置文件中有2个参数可以控制空闲连接超时断开.这2个参数是ClientAliveCountMax和ClientAliveInterval. Solaris10上设置空闲ssh连接超时断开的方 ...
- python爬虫--编码问题y
1)中文网站爬取下来的内容中文显示乱码 Python中文乱码是由于Python在解析网页时默认用Unicode去解析,而大多数网站是utf-8格式的,并且解析出来之后,python竟然再以Unicod ...
- POJ 3580 SuperMemo (FHQ_Treap)
题意:让你维护一个序列,支持以下6种操作: ADD x y d: 第x个数到第y个数加d . REVERSE x y : 将区间[x,y]中的数翻转 . REVOLVE x y t :将区间[x,y] ...
- koa的教程
https://github.com/bmcmahen/koa-mongo-sessionhttp://www.fkwebs.com/2333.htmlhttps://segmentfault.com ...
- Angular问题01 创建组件时报错、HammerJS找不到
1 利用ng创建组件时出现错误 1.1 ng g c test/testHome 1.2 问题描述 当angular应用中有多个module.ts文件时,创建组件时会出现冲突,因为有多个module. ...
- unity3d MonoDevelop引用外部自定义dll文件报错:are you missing an assembly reference?
在unity3d 编辑器 MonoDevelop 中引用外部自定义dll文件报错:are you missing an assembly reference? 因为unity还停留在.NET Fram ...
- 【摘自lvs官网】lvs介绍
Linux Virtual Server项目的目标 :使用集群技术和Linux操作系统实现一个高性能.高可用的服务器,它具有很好的可伸缩性(Scalability).可靠性(Reliability)和 ...