Implementing Data Permission Interceptor in MyBatis-Plus Using Annotations

This article explains how to create a custom annotation and a MyBatis-Plus interceptor that automatically adds data‑permission WHERE clauses based on the current user's role, covering both a basic implementation and an advanced version with role‑based scope handling.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Implementing Data Permission Interceptor in MyBatis-Plus Using Annotations

The article demonstrates a solution for adding data‑permission filtering in MyBatis‑Plus by using a custom annotation and an interceptor that modifies the SQL before execution, ensuring that only the required interfaces are intercepted.

Steps to implement:

Create a custom annotation class @interface UserDataPermission {} Implement an interceptor class that extends JsqlParserSupport and implements InnerInterceptor, overriding beforeQuery and processSelect to inject WHERE conditions.

Develop a handler class ( MyDataPermissionHandler) that builds the appropriate SQL segment based on the current user and role.

Register the interceptor in the MyBatis‑Plus plugin configuration.

Basic code examples:

Custom annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserDataPermission {}

Interceptor implementation (simplified):

public class MyDataPermissionInterceptor extends JsqlParserSupport implements InnerInterceptor {
    private MyDataPermissionHandler dataPermissionHandler;
    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        if (InterceptorIgnoreHelper.willIgnoreDataPermission(ms.getId())) return;
        PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
        mpBs.sql(this.parserSingle(mpBs.sql(), ms.getId()));
    }
    @Override
    protected void processSelect(Select select, int index, String sql, Object obj) {
        // modify SELECT ...
    }
    private void setWhere(PlainSelect plainSelect, String whereSegment) {
        // build where clause
    }
}

Handler example (basic version):

public class MyDataPermissionHandler {
    public Expression getSqlSegment(PlainSelect plainSelect, String whereSegment) {
        // obtain current user, build equality expression on creator_code
    }
}

Registering the interceptor:

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    MyDataPermissionInterceptor dataPermissionInterceptor = new MyDataPermissionInterceptor();
    dataPermissionInterceptor.setDataPermissionHandler(new MyDataPermissionHandler());
    interceptor.addInnerInterceptor(dataPermissionInterceptor);
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
}

Advanced version adds role‑based scope handling. It defines DataScope and DataPermission enums, retrieves the current user's roles via remote services, and constructs different WHERE clauses (ALL, DEPT, MYSELF) using AndExpression, InExpression, or EqualsTo as appropriate.

Usage: annotate mapper methods with @UserDataPermission to enable automatic data‑permission filtering.

Key reminders:

Ensure the interceptor is added to the MyBatis‑Plus plugin.

The filtering field (e.g., creator_code) must exist in the target tables.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendjavaspringInterceptormybatis-plusData Permission
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.