In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to achieve simple data permissions through the MyBatis custom plug-in". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve simple data permissions through MyBatis custom plug-ins".
1.mybatis Custom plug-in
When it comes to mybatis plug-ins, you always think of mybatis's paging plug-ins. It is true that if you use mybatis in development, you will generally use it. It can add paging query conditions after our sql statement to achieve the effect of paging query.
① configuration
Since mybatis is configured based on the xml plug-in, we need to configure our own plug-in in xml
/ / the interception of the full class name of the custom plug-in ② API
Take a look at a picture first. Mybatis mainly provides the following four interfaces to support interception.
Write DataScopeInterceptor (you need to implement the Interceptor interface)
@ Intercepts ({@ Signature (type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}) public class DataScopeInterceptor implements Interceptor {/ / every time the operation is performed, @ Override public Object intercept (Invocation invocation) throws Throwable {/ / TODO: your own business process return invocation.proceed () } / / the main purpose of this interceptor is to generate a proxy in the interceptor chain @ Override public Object plugin (Object o) {return Plugin.wrap (o, this);} / / when the plug-in is initialized, it is called only once. The properties of the plug-in configuration are set to @ Override public void setProperties (Properties properties) {}}.
Look at this note.
@ Signature (type = StatementHandler.class, / / this refers to which interface to intercept method = "prepare", / / this is the method in the intercepting interface, args = {Connection.class, Integer.class} / / the parameter list of the intercepting method can be found in StatementHandler)
Let's start the project and enter our plug-in when executing the sql query. Now I've defined an empty plug-in.
Ps:mybatis can define multiple plug-ins at the same time. These plug-ins adopt the responsibility chain mode and call the next plug-in one by one through the proxy object for execution.
two。 Data permissions (take query as an example only)
In project development, most projects have permissions-related considerations. when it comes to permissions, they are generally divided into two categories, data permissions and functional permissions. Data permissions generally refer to different roles or users, query different data, and filter different conditions of the same data table or data source. The function permission is more about the access to the function menu. In different projects, the permission design is also different, which is closely related to the system business and architecture design. It is very difficult to do a good job of permissions. What I'm doing here is just a simulation of data permissions. It does not involve the specific implementation. There is no same solution for this area in the first place.
Classification of ① authorizations
Here, I divide data permissions into two categories, detail authorization and conditional authorization.
Detailed authorization: authorize a table data through id, for example, if there is a commodity table, you can authorize the id of a specified product to a specified user or role, so that the user or role can query the specified product.
Select * from product where id = 1
Conditional authorization: you can authorize a user or role by specifying scope query criteria
Select * from product where name like'% iphone%'
The above two sql clearly show the difference and relationship between the two authorization methods. We can't help thinking that detailed authorization can also be achieved by conditional authorization to achieve the same effect. Indeed, we only explain the different authorization methods for two days. In fact, in the real environment, there may be other forms of authorization.
Above we can deal with sql by customizing the mybatis plug-in. So, data permissions are nothing more than getting sql in a custom plug-in. Concatenate different filtering conditions after the sql statement to achieve data filtering. The real business scenario is more complex. Most of the time, it's not just splicing. The handling of sql is also a waste of effort. Let's look at the specific implementation.
② implementation of different authorization types
Data permission API. Only one method definition of getsql is written here. The parameter is the original sql, and the returned value is the processed sql.
Public interface DataScopeInterface {/ * get sql * @ return * / String getSql (String sql);}
DataScopeInterface has two different implementation classes, details and conditions
@ Component ("grantDataScope") @ Slf4jpublic class GrantDataScope implements DataScopeInterface {/ / details Authorization implementation @ Override public String getSql (String sql) {/ / here is the id to get the currently logged-in user. I have defined a login blocker to save the currently logged-in user through ThreadLocal. The code will not be written. It is relatively simple that String userId = LoginHandlerInterceptor.userLoginThreadLocal.get (); / / A user whose id is 1 is simulated to concatenate the filter condition if ("1" .equals (userId)) {if (sql.toLowerCase (). Contains ("where")) {sql + = ">" after the query statement.
Conditional authorization
@ Component ("ruleDataScope") @ Slf4jpublic class RuleDataScope implements DataScopeInterface {/ / conditional authorization implementation public String getSql (String sql) {String userId = LoginHandlerInterceptor.userLoginThreadLocal.get () / / simulate users with id 2 plus data if ("2" .equals (userId)) {if (sql.toLowerCase () .contains ("where")) {sql + = "and name like'% iphone%'";} else {sql + = "where name like'% iphone%'" in name }} log.info ("rule:" + sql); return sql;}} ③ plug-in logic implementation
Let's write the business implementation logic in the custom plug-in. Because our different authorization types are bean managed by spring, we can use the policy pattern to achieve the scalability of authorization rules. With different authorization rules, you only need to implement the DataScopeInterface interface.
Public Object intercept (Invocation invocation) throws Throwable {StatementHandler statementHandler = (StatementHandler) invocation.getTarget (); MetaObject metaStatementHandler = SystemMetaObject.forObject (statementHandler); String userName = LoginHandlerInterceptor.userLoginThreadLocal.get (); / / sql statement type Object sqlCommandType = metaStatementHandler.getValue ("delegate.mappedStatement.sqlCommandType") / / only consider querying if (SqlCommandType.SELECT.equals (sqlCommandType)) {/ / get sql String sql = String.valueOf (metaStatementHandler.getValue ("delegate.boundSql.sql")); / / get the collection of implementation classes of DataScopeInterface and iterate through the formatting Map dataScopeInterfaceMap = SpringContextUtils.getBeanOfType (DataScopeInterface.class) of sql; Collection dataScopeInterfaces = dataScopeInterfaceMap.values () For (DataScopeInterface dataScopeInterface: dataScopeInterfaces) {sql = dataScopeInterface.getSql (sql);} log.info ("sql->" + sql); / / reset sql metaStatementHandler.setValue ("delegate.boundSql.sql", sql);} return invocation.proceed ();} ⑤ verification
Start the project, simulate the login of the user whose id is 1, and return a record, achieving the effect of filtering.
2019-08-24 14 Preparing 07select 05496 DEBUG (BaseJdbcLogger.java:145)-= > Preparing: select * from product where id = 1 2019-08-24 14V 07V 05496 DEBUG (BaseJdbcLogger.java:145)-= > Parameters: 2019-08-24 14V 07V 05498 DEBUG (BaseJdbcLogger.java:145)-Preparing: select * from product where where name like'% iphone%' 2019-08-24 1414 VM 099017 DEBUG (BaseJdbcLogger.java:145)-= > Parameters: 2019-08-24 14RV 099020 DEBUG (BaseJdbcLogger.java:145)-
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.