Mybatis拦截器实现公共字段填充

在使用MyBatis进行数据库操作时,通常需要对一些公共字段进行自动填充,例如创建时间、更新时间、创建人等。为了简化这些操作,可以使用MyBatis拦截器来实现公共字段的自动填充。本文将详细介绍如何实现这一功能。

实现步骤

1. 创建拦截器

首先,我们需要创建一个MyBatis拦截器。MyBatis提供了 Interceptor接口,我们可以通过实现该接口来定义自己的拦截逻辑。

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Date;
import java.util.Properties;

@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class CommonFieldInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (invocation.getArgs().length > 1) {
            Object parameter = invocation.getArgs()[1];
            if (parameter instanceof BaseEntity) {
                BaseEntity entity = (BaseEntity) parameter;
                if (isInsertOperation(invocation)) {
                    entity.setCreateTime(new Date());
                    entity.setUpdateTime(new Date());
                } else if (isUpdateOperation(invocation)) {
                    entity.setUpdateTime(new Date());
                }
            }
        }
        return invocation.proceed();
    }

    private boolean isInsertOperation(Invocation invocation) {
        String methodName = ((MappedStatement) invocation.getArgs()[0]).getId();
        return methodName.contains("insert");
    }

    private boolean isUpdateOperation(Invocation invocation) {
        String methodName = ((MappedStatement) invocation.getArgs()[0]).getId();
        return methodName.contains("update");
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可选:设置属性
    }
}
​
 
 

2. 基础实体类

为了统一管理公共字段,我们需要创建一个基础实体类,所有需要自动填充公共字段的实体类都应继承该类。

import java.util.Date;

public class BaseEntity {
    private Date createTime;
    private Date updateTime;

    // getters and setters
    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}
​
 
 

3. 配置拦截器

在MyBatis配置文件中注册拦截器。

<plugins>
    <plugin interceptor="com.example.mybatis.interceptor.CommonFieldInterceptor"/>
</plugins>
 
 

4. 使用示例

创建一个继承 BaseEntity的实体类,并在Mapper中使用该实体类进行数据库操作。

public class User extends BaseEntity {
    private Long id;
    private String name;

    // getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
​
 
 
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;

public interface UserMapper {
    @Insert("INSERT INTO user (name, create_time, update_time) VALUES (#{name}, #{createTime}, #{updateTime})")
    void insert(User user);

    @Update("UPDATE user SET name = #{name}, update_time = #{updateTime} WHERE id = #{id}")
    void update(User user);
}
​
 
 

关键点分析

拦截器

拦截器用于拦截MyBatis执行的SQL操作,通过 @Intercepts和 @Signature注解指定拦截的对象和方法。在 intercept方法中,我们通过判断操作类型(插入或更新)来填充相应的公共字段。

基础实体类

基础实体类 BaseEntity包含了需要自动填充的公共字段及其getter和setter方法。所有需要自动填充公共字段的实体类都应继承该类。

配置和使用

在MyBatis配置文件中注册拦截器,并在Mapper中使用继承自 BaseEntity的实体类进行数据库操作,确保公共字段能够自动填充。

分析说明表

步骤 描述
创建拦截器 实现 Interceptor接口,通过拦截MyBatis操作自动填充公共字段
基础实体类 定义包含公共字段的基础实体类,所有需要自动填充的实体类都继承该类
配置拦截器 在MyBatis配置文件中注册拦截器
使用示例 创建实体类和Mapper进行数据库操作,验证自动填充功能

思维导图

MyBatis拦截器实现公共字段填充
|
|-- 创建拦截器
|   |-- 实现Interceptor接口
|   |-- 判断操作类型(插入或更新)
|   |-- 填充公共字段
|
|-- 基础实体类
|   |-- 定义公共字段
|   |-- 继承BaseEntity
|
|-- 配置拦截器
|   |-- MyBatis配置文件中注册拦截器
|
|-- 使用示例
|   |-- 创建实体类
|   |-- 创建Mapper
|   |-- 执行数据库操作
posted @   淘气的布谷鸟  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示