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对象 ...
随机推荐
- set和get的用法
import { Map} from 'immutable'; let a = Map({ select: 'users', filter: Map({ name: 'Cam' }) }) let b ...
- 拨打电话demo
- (IBAction)btnClick:(id)sender { UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:nil d ...
- springmvc 加载静态文件失败
header.jsp,部分代码 <head> <title>QA|VIS_PLATFORM</title> <meta content="width ...
- Python网络编程中的select 和 poll I/O复用的简单使用
首先列一下,sellect.poll.epoll三者的区别 select select最早于1983年出现在4.2BSD中,它通过一个select()系统调用来监视多个文件描述符的数组,当select ...
- 蓝桥杯 算法训练 ALGO-129 特殊的数字四十
算法训练 特殊的数字四十 时间限制:1.0s 内存限制:256.0MB 特殊的数字四十 问题描述 1234是一个非常特殊的四位数,因为它的各位数之和为10,编程求所有这样的四位十进制数. 输出 ...
- Day3-Python基础3--默认参数和参数组
一.默认参数 先看下下面的代码: def stu_register(name,age,country,course): print("----注册学生信息------") prin ...
- net.sf.json.JSONObject 和org.json.JSONObject
参考 net.sf.json.JSONObject 和org.json.JSONObject 的差别
- ie6 ie7下报脚本错误"Expected identifier, string or number" 的原因和解决方法
在IE6和ie7里面,脚本报错"Expected identifier, string or number" 写下这个是个之前我已经很头疼了,因为我的代码在其他浏览器里都是正常的, ...
- jackson 进行json与java对象转换 之二
主要用于测试学习用jackson包实现json.对象.Map之间的转换. 1.准备测试用的Java类 (1)Link类 package test; /** * Description: 联系方式,被u ...
- [Python Study Notes]堆叠柱状图绘制
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...