Are you still foolishly manually adding the creator and creation time in sql? A general skill that senior development engineers have to know!

Posted by not_john on Mon, 17 Jan 2022 12:11:04 +0100

background

In the process of database design, we often add some general fields to database tables, such as creator, creation time, modifier and modification time. Sometimes, in the design process of some companies, each table is forced to contain these basic information in order to record some basic log records during data operation. According to the normal operation, the common practice is to write this information together with the basic attribute information of the object into the database when inputting and writing sql. Of course, this is also a common operation. This writing method is understandable, but for a senior developer, if all tables are operated in this way, it will be a little verbose and there are many data tables, It's not worth the loss. In fact, there is a simpler way. You should be familiar with the spring framework, which is used by almost every company. One of the classic application scenarios of aop idea (aspect programming) is logging. Combined with aop idea, this paper focuses on how to use aspect programming idea to realize the creation of creator, creation time, updater Basic information such as update time is written to the database.

Core code

@Aspect
@Component
@Configuration
public class CommonDaoAspect {
    
    private static final String creater = "creater";
    private static final String createTime = "createTime";
    private static final String updater = "updater";
    private static final String updateTime = "updateTime";

    @Pointcut("execution(* com.xx.xxxx.*.dao.*.update*(..))")
    public void daoUpdate() {
    }

    @Pointcut("execution(* com.xx.xxxx.*.dao.*.insert*(..))")
    public void daoCreate() {
    }

    @Around("daoUpdate()")
    public Object doDaoUpdate(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return pjp.proceed();
        }
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        String username = getUserName();
        if (token != null && username != null) {
            Object[] objects = pjp.getArgs();
            if (objects != null && objects.length > 0) {
                for (Object arg : objects) {
                    BeanUtils.setProperty(arg, updater, username);
                    BeanUtils.setProperty(arg, updateTime, new Date());
                }
            }
        }
        Object object = pjp.proceed();
        return object;

    }

    @Around("daoCreate()")
    public Object doDaoCreate(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return pjp.proceed();
        }
        Object[] objects = pjp.getArgs();
        if (objects != null && objects.length > 0) {
            for (Object arg : objects) {
                String username = getUserName();
                if (username != null) {
                    if (StringUtils.isBlank(BeanUtils.getProperty(arg, creater))) {
                        BeanUtils.setProperty(arg, creater, username);
                    }
                    if (StringUtils.isBlank(BeanUtils.getProperty(arg, createTime))) {
                        BeanUtils.setProperty(arg, createTime, new Date());
                    }
                }
            }
        }
        Object object = pjp.proceed();
        return object;
    }

    private String getUserName() {
        return UserUtils.getUsername();
    }
}

Code introduction and notes

1. Code introduction

The core code declares a CommonDaoAspect aspect class, and the entity class declares four core methods and a method to obtain user name information. UserUtils is a tool class declared in the project, which contains some basic information such as user id and name. You can define it according to your actual situation instead of moving according to the Department. Among the four core methods, the @ Pointcut annotation is added to daoUpdate and daoCreate. The annotation determines which methods under the dao directory in the project package execute the aspect method by declaring regular expressions. The @ Around annotation is added to the doDaoUpdate and doDaoCreate methods. The above two methods are introduced into the annotation to represent the surround notification. Enhancement processing is performed before and after the completion of the corresponding file target method in our dao directory.

2. Notes

  • @Aspect: declare aspect classes, which can define pointcuts and notifications
  • @Component: indicates that this class is an object managed by spring
  • @Pointcut: the pointcut point, which declares the timing of the pointcut through regular expressions. In this paper, the pointcut information is added during the execution of the target method (that is, the method containing the insert or update string in the entity class under the dao directory in the project), that is, the creator and new person are added when adding or updating.
  • @Around: surround the notification and enhance it before and after the target method is completed. In this case, it means adding parameter information when the doCreate and doUpdate methods are executed

Note: execution(* com.xx.xxxx..dao..update * (..)) Represents a method starting with update in any file in the dao directory

execution(* com.xx.xxxx..dao..insert*(..)) Represents a method starting with insert in any file in the Dao directory

last

Recently, I compiled a complete set of "summary of Java core knowledge points". To be honest, as a java programmer, you should take a good look at this material whether you need an interview or not. Kwai won't lose my hand. Many of my fans got the Offer of Tencent's byte express.

Enter[ Java advanced road group ], find the administrator to get Oh -!

Topics: Java Programming Database Mybatis Spring