Using easy-data-scope for Dynamic SQL Data Permissions in Spring Boot
This guide demonstrates how to integrate the easy-data-scope library into a Spring Boot project to implement dynamic, annotation‑driven SQL data permissions with MyBatis, covering project setup, dependency configuration, core interfaces, annotation options, and practical query examples.
easy-data-scope is a data‑permission framework that injects dynamic SQL at runtime, supporting MyBatis, MyBatis‑plus, and MyBatis‑flex, and allows developers to apply permissions simply by adding annotations to service methods.
Project setup includes creating a simple user table, adding Maven dependencies for Spring Boot, MyBatis‑plus, and the core ds-mybatis library, defining the main class, and configuring application.yml with datasource and MyBatis settings.
The core interface DataScopeFindRule is implemented to fetch DataScopeInfo objects from the database based on the current user session. The @DataScope annotation can be placed on service methods to specify which permission keys to apply, the logical operator (WHERE/AND/OR), whether to merge conditions, and optional SQL templates.
@DataScope(keys = {"USER_LIST_AGE111", "USER_LIST_AGE222"}, merge = true, logical = SqlConsts.WHERE)
public List
getAll4() {
return userMapper.selectList(null);
}Examples show how to restrict queries to a single ID, a specific age, or multiple ages using the merge attribute, which automatically combines equal operators into an IN clause.
SELECT id,username,age FROM user WHERE (user.age IN (111, 222))The flag attribute can be used in MyBatis XML to insert a placeholder {{_DATA_SCOPE_FLAG}} that the framework replaces at runtime.
@DataScope(keys = {"USER_LIST_AGE111", "USER_LIST_AGE222"}, flag = true)
List
getAll5();Custom templates allow complex conditions, e.g., "{{USER_LIST_AGE111}} OR {{USER_LIST_AGE222}}" , which the framework expands into the appropriate SQL.
@DataScope(keys = {"USER_LIST_AGE111", "USER_LIST_AGE222"}, template = "{{USER_LIST_AGE111}} OR {{USER_LIST_AGE222}}")
List
getAll6();The article concludes with the full SQL generated for each scenario and provides a link to the project’s GitHub repository for further exploration.
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
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.