creatby,updateby等字段自动填充
每个字段在插入数据库,或者更新时都要在serviceimpl层对creatby,updateby等字段进行填充,这个太繁琐了,以下两种方法可以实现字段的自动填充。本项目使用第一种。
方法一:
首先创建一个autofillinterceptor类。下面会对代码逐行分析。
以下代码也可以直接复制粘贴,但前提是你的实体类中的自动填充的字段和下面四个静态常量名字一样。
@component
@intercepts({
@signature(type = executor.class, method = "update", args = {mappedstatement.class, object.class})
})
public class autofillinterceptor implements interceptor {
private static final string create_by = "createdby";
private static final string update_by = "updatedby";
private static final string create_time = "createdat";
private static final string update_time = "updatedat";
@override
public object intercept(invocation invocation) throws throwable {
object[] args = invocation.getargs();
mappedstatement ms = (mappedstatement) args[0];
sqlcommandtype sqlcommandtype = ms.getsqlcommandtype();
object parameter = args[1];
if(parameter != null && sqlcommandtype!=null){
if(sqlcommandtype.insert.equals(sqlcommandtype)){
if(parameter instanceof mappermethod.parammap){
mappermethod.parammap parammap = (mappermethod.parammap) parameter;
arraylist list= (arraylist) parammap.get("list");
list.foreach(v->{
setfieldvalbyname(create_time, localdatetime.now(), v);
setfieldvalbyname(update_time, localdatetime.now(), v);
});
parammap.put("list", list);
}else{
// 单条插入的情况
// 设置创建人和创建时间字段值
setfieldvalbyname(create_time, localdatetime.now(), parameter);
setfieldvalbyname(update_time, localdatetime.now(), parameter);
}
}
else if(sqlcommandtype.update.equals(sqlcommandtype)){
// 更新操作
// 设置更新人和更新时间字段值
setfieldvalbyname(update_time, localdatetime.now(), parameter);
}
}
// 继续执行原始方法
return invocation.proceed();
}
private void setfieldvalbyname(string fieldname, object fieldval, object parameter) {
metaobject metaobject = systemmetaobject.forobject(parameter);
if (metaobject.hassetter(fieldname)) {
metaobject.setvalue(fieldname, fieldval);
}
}
@override
public void setproperties(properties properties) {
interceptor.super.setproperties(properties);
}
@override
public object plugin(object target) {
return interceptor.super.plugin(target);
}
}
代码结构与作用
这是一个实现了mybatis拦截器(interceptor接口)的类autofillinterceptor,用于在执行sql操作(insert或update)时,自动填充一些通用字段,比如创建时间(createdat)、更新时间(updatedat)等。
在企业级项目中,通常需要记录数据的创建时间和修改时间,这个拦截器就是为了解决这种需求,在新增和修改数据时自动填充这些字段。下面我们来逐行分析代码。
代码逐行解析
@component
@intercepts({
@signature(type = executor.class, method = "update", args = {mappedstatement.class, object.class})
})
@component:spring的注解,将这个类注册为一个spring bean,便于管理。@intercepts:mybatis的注解,声明这是一个拦截器,并指定要拦截的目标。@signature:定义拦截器的具体拦截方法。type = executor.class:表示拦截mybatis的executor类。method = "update":表示拦截update方法,这个方法用于执行更新操作(包括insert、update、delete)。args = {mappedstatement.class, object.class}:指定update方法的参数类型,即sql映射信息mappedstatement和参数对象object。
public class autofillinterceptor implements interceptor {
- 这几行定义了一些常量,分别表示字段名称,如创建者、修改者、创建时间和修改时间。这些常量将在拦截逻辑中用来自动填充字段。
@override
public object intercept(invocation invocation) throws throwable {
object[] args = invocation.getargs();
mappedstatement ms = (mappedstatement) args[0];
sqlcommandtype sqlcommandtype = ms.getsqlcommandtype();
object parameter = args[1];
intercept方法是拦截器的核心逻辑。object[] args = invocation.getargs():获取拦截方法的参数。mappedstatement ms = (mappedstatement) args[0]:获取mappedstatement,包含了有关sql语句的信息。sqlcommandtype sqlcommandtype = ms.getsqlcommandtype():获取sql的操作类型(insert、update、delete)。object parameter = args[1]:获取参数对象,通常是用户要插入或更新的数据。
if(parameter != null && sqlcommandtype != null){
- 检查参数是否为空,并确认操作类型是否非空,确保有必要继续执行后续操作。
if(sqlcommandtype.insert.equals(sqlcommandtype)){
if(parameter instanceof mappermethod.parammap){
mappermethod.parammap parammap = (mappermethod.parammap) parameter;
arraylist list= (arraylist) parammap.get("list");
list.foreach(v -> {
setfieldvalbyname(create_time, localdatetime.now(), v);
setfieldvalbyname(update_time, localdatetime.now(), v);
});
parammap.put("list", list);
} else {
// 单条插入的情况
// 设置创建人和创建时间字段值
setfieldvalbyname(create_time, localdatetime.now(), parameter);
setfieldvalbyname(update_time, localdatetime.now(), parameter);
}
}
if (sqlcommandtype.insert.equals(sqlcommandtype)):如果当前sql是insert操作:if (parameter instanceof mappermethod.parammap):判断参数是否是mappermethod.parammap类型,这通常用于批量插入。arraylist list = (arraylist) parammap.get("list"):从参数map中获取名为list的参数,这是批量插入的数据集合。list.foreach(v -> {...}):对每个元素进行操作,调用setfieldvalbyname方法设置createdat和updatedat为当前时间。
else部分:处理单条插入的情况,直接给parameter对象设置创建时间和更新时间。
else if(sqlcommandtype.update.equals(sqlcommandtype)){
// 更新操作
// 设置更新人和更新时间字段值
setfieldvalbyname(update_time, localdatetime.now(), parameter);
}
else if (sqlcommandtype.update.equals(sqlcommandtype)):如果当前sql是update操作:- 使用
setfieldvalbyname方法将updatedat字段设置为当前时间。
- 使用
}
// 继续执行原始方法
return invocation.proceed();
}
- 最终通过
invocation.proceed()调用被拦截的方法,继续执行原始的数据库操作。
private void setfieldvalbyname(string fieldname, object fieldval, object parameter) {
metaobject metaobject = systemmetaobject.forobject(parameter);
if (metaobject.hassetter(fieldname)) {
metaobject.setvalue(fieldname, fieldval);
}
}
setfieldvalbyname方法用于设置对象中指定字段的值:metaobject metaobject = systemmetaobject.forobject(parameter):创建metaobject,用于操作传入对象的元数据。if (metaobject.hassetter(fieldname)):检查对象是否有对应字段的setter方法。metaobject.setvalue(fieldname, fieldval):如果有setter方法,则设置字段的值。
@override
public void setproperties(properties properties) {
interceptor.super.setproperties(properties);
}
@override
public object plugin(object target) {
return interceptor.super.plugin(target);
}
}
setproperties和plugin方法是interceptor接口的默认实现,plugin方法用于生成代理对象。
总结
- 这个拦截器的作用是自动填充
createdat和updatedat字段,以便在执行insert和update操作时自动记录创建和更新时间。 - 主要拦截
executor的update方法,通过判断sql类型来确定是insert还是update操作,从而设置相应字段。 - 使用了mybatis的
metaobject工具类来动态操作参数对象的字段值。
通过这个拦截器,开发者不需要在业务代码中手动设置createdat和updatedat,大大减少了重复代码,也保证了这些公共字段的一致性和正确性。
方法二:
这个方法是使用自定义注解来写的,所以要在需要填充的sql上加上这个注解。这个可能更加灵活更加简单把。
公共字段自动填充
技术点:枚举、注解、aop、反射
创建时间、修改时间、创建人、修改人这4个公共字段。
为mapper方法加注解autofill,标识需要进行公共字段自动填充
自定义切面类autofillaspect,统一拦截加入了autofill注解的方法,通过反射为公共字段赋值。
在mapper的方法上接入autofill注解。
public enum operationtype {
更新操作
update,
插入操作
insert
}
@target(elementtype.method)当前注解加在什么位置
@retention(retentionpolicy.runtime)
public @interface autofill {
//数据库操作类型:update insert
operationtype value();
}
补充注解基本知识
public @interface myannotation {
// 定义注解的成员
string value(); // 这是一个名为"value"的成员
int count() default 1; // 这是一个名为"count"的成员,带有默认值
}
@myannotation(value = "hello", count = 3)
public class myclass {
// 类的代码
}
对于autofillaspect类切点、execution表达式
/**
* 自定义切面,实现公共字段自动填充处理逻辑
*/
@aspect
@component
@slf4j
public class autofillaspect {
/**
* 切入点
*/
所有的类,所有的方法,所有的参数类型
@pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.autofill)")
public void autofillpointcut(){}
/**
* 前置通知,在通知中进行公共字段的赋值
*/
@before("autofillpointcut()")指定切入点
public void autofill(joinpoint joinpoint){连接点
log.info("开始进行公共字段自动填充...");
//获取到当前被拦截的方法上的数据库操作类型
methodsignature signature = (methodsignature) joinpoint.getsignature();//方法签名对象
autofill autofill = signature.getmethod().getannotation(autofill.class);//获得方法上的注解对象
operationtype operationtype = autofill.value();//获得数据库操作类型
//获取到当前被拦截的方法的参数--实体对象 做一个约定,实体对象放第一个
object[] args = joinpoint.getargs();
if(args == null || args.length == 0){
return;
}
object entity = args[0];实体
//准备赋值的数据
localdatetime now = localdatetime.now();
long currentid = basecontext.getcurrentid();
//根据当前不同的操作类型,为对应的属性通过反射来赋值
if(operationtype == operationtype.insert){
//为4个公共字段赋值
try {
method setcreatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_create_time, localdatetime.class);
method setcreateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_create_user, long.class);
method setupdatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_update_time, localdatetime.class);
method setupdateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_update_user, long.class);
//通过反射为对象属性赋值
setcreatetime.invoke(entity,now);
setcreateuser.invoke(entity,currentid);
setupdatetime.invoke(entity,now);
setupdateuser.invoke(entity,currentid);
} catch (exception e) {
e.printstacktrace();
}
}else if(operationtype == operationtype.update){
//为2个公共字段赋值
try {
method setupdatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_update_time, localdatetime.class);
method setupdateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_update_user, long.class);
//通过反射为对象属性赋值
setupdatetime.invoke(entity,now);
setupdateuser.invoke(entity,currentid);
} catch (exception e) {
e.printstacktrace();
}
}
}
}
使用
@autofill(value = operationtype.update) void update(employee employee);
自定义切面:实现公共字段的自动填充
这段代码使用了 spring aop(面向切面编程)来实现对数据库操作时,自动填充一些公共字段,例如创建时间、更新时间、创建人、更新人等。接下来,我们逐行解析这段代码,以帮助你理解各个部分的功能和实现逻辑。
代码结构概览
@aspect
@component
@slf4j
public class autofillaspect {
// 切入点
@pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.autofill)")
public void autofillpointcut(){}
// 前置通知
@before("autofillpointcut()")
public void autofill(joinpoint joinpoint){
log.info("开始进行公共字段自动填充...");
...
}
}
这段代码定义了一个切面 autofillaspect,它会在符合条件的数据库操作方法执行之前,通过前置通知 (@before) 自动对某些公共字段进行填充。
注解解释
@aspect:表示当前类是一个切面类,用于定义通知和切入点。@component:把这个切面类注册为 spring 容器中的一个组件。@slf4j:用来启用日志功能,以方便调试和记录信息。
切入点定义
@pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.autofill)")
public void autofillpointcut(){}
解释:
@pointcut:用于定义一个切入点,描述哪些方法需要被切面逻辑拦截。execution(* com.sky.mapper.*.*(..)):匹配com.sky.mapper包下的所有类和所有方法,(..)表示任意参数类型和数量。&& @annotation(com.sky.annotation.autofill):表示只拦截被@autofill注解标记的方法。
通过这种定义,只有符合指定包下的类且有 @autofill 注解的方法,才会被切面逻辑拦截。
前置通知(before advice)
@before("autofillpointcut()")
public void autofill(joinpoint joinpoint) {
log.info("开始进行公共字段自动填充...");
...
}
- @before("autofillpointcut()"):这是前置通知,表示在切入点所匹配的方法执行之前,执行 autofill() 方法。
- joinpoint joinpoint:joinpoint 是一个连接点,表示被拦截的方法,允许获取到目标方法的一些信息,比如方法名和参数等。
获取注解和方法信息
methodsignature signature = (methodsignature) joinpoint.getsignature(); autofill autofill = signature.getmethod().getannotation(autofill.class); operationtype operationtype = autofill.value();
methodsignature signature = (methodsignature) joinpoint.getsignature();:获取当前拦截的方法的签名信息,转换为methodsignature类型。autofill autofill = signature.getmethod().getannotation(autofill.class);:获取方法上的@autofill注解对象。operationtype operationtype = autofill.value();:获取注解中指定的数据库操作类型(例如 insert 或 update)。
获取方法参数
object[] args = joinpoint.getargs();
if (args == null || args.length == 0) {
return;
}
object entity = args[0];
object[] args = joinpoint.getargs();:获取当前被拦截的方法的参数。if (args == null || args.length == 0):如果没有参数,直接返回。object entity = args[0];:假设第一个参数是实体对象,用于操作数据库。这里有一个约定,即实体对象总是第一个参数。
准备赋值的数据
localdatetime now = localdatetime.now(); long currentid = basecontext.getcurrentid();
localdatetime now = localdatetime.now();:获取当前时间,用于填充创建时间和更新时间。long currentid = basecontext.getcurrentid();:获取当前操作用户的 id,用于填充创建人和更新人信息。
根据操作类型进行赋值
插入操作(insert)
if (operationtype == operationtype.insert) {
try {
method setcreatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_create_time, localdatetime.class);
method setcreateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_create_user, long.class);
method setupdatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_update_time, localdatetime.class);
method setupdateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_update_user, long.class);
setcreatetime.invoke(entity, now);
setcreateuser.invoke(entity, currentid);
setupdatetime.invoke(entity, now);
setupdateuser.invoke(entity, currentid);
} catch (exception e) {
e.printstacktrace();
}
}
if (operationtype == operationtype.insert):如果数据库操作类型是插入(insert)。- 通过反射的方式获取实体类中的
setcreatetime、setcreateuser、setupdatetime和setupdateuser方法。 invoke()方法用于调用这些 setter 方法并传入相应的值,完成公共字段的赋值。
更新操作(update)
else if (operationtype == operationtype.update) {
try {
method setupdatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_update_time, localdatetime.class);
method setupdateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_update_user, long.class);
setupdatetime.invoke(entity, now);
setupdateuser.invoke(entity, currentid);
} catch (exception e) {
e.printstacktrace();
}
}
else if (operationtype == operationtype.update):如果操作类型是更新(update)。- 这里只需填充更新相关的字段,即更新时间和更新人。
小结
这段代码实现了对数据库操作的公共字段自动填充,具体如下:
- 定义一个切面
autofillaspect,用于拦截特定包中的方法,并且方法需要用@autofill注解进行标记。 - 使用 aop 的前置通知在方法执行前进行字段自动填充。
- 通过反射机制获取实体对象的方法并进行赋值,根据操作类型填充不同的字段。
这使得代码变得更加简洁和可维护,减少了重复的公共字段赋值逻辑,也方便对创建时间、更新时间等公共属性的一致性管理。
以上就是springboot实现字段自动填充的两种方式的详细内容,更多关于springboot字段自动填充的资料请关注代码网其它相关文章!
发表评论