掘客神器:Springboot高效实现字段自动填充
2023-08-17 20:03:40
Springboot:告别手动字段填充,解锁高效开发姿势
前言
作为一名开发人员,你是否曾为重复繁琐的字段填充而烦恼?在Springboot开发中,字段自动填充是一个常见需求,无论是创建实体类还是更新数据库,都需要对一些公共字段,如创建时间、更新时间、创建人、更新人等进行填充。
传统的手动填充方式不仅效率低下,还容易出错。为了解决这一难题,Springboot提供了两种简单有效的方式来实现字段自动填充:自定义注解和使用mybatis plus提供的方法。
自定义注解
1. 创建注解
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoFill {
//自动填充类型
FillType fillType();
//自动填充的值
String value() default "";
}
2. 创建枚举
public enum FillType {
INSERT,
UPDATE,
BOTH
}
3. 创建切面类
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AutoFillAspect {
@Around("execution(* set*(..)) && @annotation(autoFill)")
public Object around(ProceedingJoinPoint joinPoint, AutoFill autoFill) throws Throwable {
//获取实体类属性名
String fieldName = joinPoint.getSignature().getName().substring(3);
//获取实体类
Object target = joinPoint.getTarget();
//获取自动填充的类型
FillType fillType = autoFill.fillType();
//获取自动填充的值
String value = autoFill.value();
//判断自动填充的类型
switch (fillType) {
case INSERT:
//如果是插入,则判断实体类属性值是否为空,如果为空,则自动填充
if (target.getClass().getMethod("get" + fieldName).invoke(target) == null) {
target.getClass().getMethod("set" + fieldName, String.class).invoke(target, value);
}
break;
case UPDATE:
//如果是更新,则判断实体类属性值是否为空,如果为空,则不自动填充
if (target.getClass().getMethod("get" + fieldName).invoke(target) != null) {
target.getClass().getMethod("set" + fieldName, String.class).invoke(target, value);
}
break;
case BOTH:
//如果是插入或更新,则自动填充
target.getClass().getMethod("set" + fieldName, String.class).invoke(target, value);
break;
}
//执行原方法
return joinPoint.proceed();
}
}
4. mapper方法中添加注解
@Insert("insert into user (name, age) values (#{name}, #{age})")
@AutoFill(fillType = FillType.INSERT, value = "now()")
public int insertUser(User user);
mybatis plus方法
mybatis plus提供了@TableField注解,可以轻松实现字段自动填充。该注解包含fill属性,该属性表示自动填充的类型,可以是INSERT、UPDATE或BOTH。
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
public class User {
@TableId
private Long id;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
}
结语
使用Springboot实现字段自动填充,可以大大提高开发效率,减少出错的几率。无论你是选择自定义注解还是使用mybatis plus提供的方法,都可以轻松实现字段自动填充,让你告别重复繁琐的代码,专注于业务逻辑的开发。
常见问题解答
-
什么是字段自动填充?
字段自动填充是指在创建实体类或更新数据库时,自动填充一些公共字段,如创建时间、更新时间、创建人、更新人等。
-
为什么需要字段自动填充?
手动填充字段既耗时又容易出错。自动填充可以节省时间,减少错误,提高开发效率。
-
自定义注解和mybatis plus方法哪种更好?
两种方法都有其优缺点。自定义注解更灵活,但需要编写切面类。mybatis plus方法更简单,但灵活性较差。
-
是否可以在一个项目中同时使用自定义注解和mybatis plus方法?
可以。自定义注解和mybatis plus方法不冲突,可以根据实际需求选择使用。
-
如何避免字段自动填充造成数据不一致?
在使用字段自动填充时,需要考虑并发场景,避免数据不一致。例如,使用乐观锁或分布式锁来确保数据的一致性。