欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis新增对象自动生成uuid方案

程序员文章站 2022-10-18 23:45:15
mybatis新增对象时, 使用拦截器自动生成uuid方案有了它不再去xml中手动添加selectKey了, 生成id方案实现类自行实现, 实现IdGenerator接口便可, 主要代码由公司同事编写, 我进行改造 使用时可以在id字段上添加@Id注解, 也可以在getId方法上添加或者不添加, 但 ......

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");
	}

}