萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> mybatis interceptor 處理查詢參數及查詢結果的實例代碼

mybatis interceptor 處理查詢參數及查詢結果的實例代碼

這篇文章介紹了mybatis interceptor 處理查詢參數及查詢結果的實例代碼,非常實用,有興趣的同學可以參考一下。  代碼如下 復制代碼

/**

 * Created by windwant on 2017/1/12.

 */

@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})

})

publicclassEncryptInterceptorimplementsInterceptor {

  publicstaticfinalLogger logger = LoggerFactory.getLogger(EncryptInterceptor.class);

  @Override

  publicObject intercept(Invocation invocation)throwsThrowable {

    dealParameter(invocation);

    Object returnValue = invocation.proceed();

    dealReturnValue(returnValue);

    returnreturnValue;

  }

  //查詢參數加密處理

  privatevoiddealParameter(Invocation invocation) {

    MappedStatement statement = (MappedStatement) invocation.getArgs()[0];

    String mapperl = ConfigUtils.get("mybaits.mapper.path");

    String methodName = statement.getId().substring(statement.getId().indexOf(mapperl) + mapperl.length() +1);

    if(methodName.startsWith("UserBaseMapper")){

      if(methodName.equals("UserBaseMapper.updateDriver")){

        ((Driver) invocation.getArgs()[1]).encrypt();

      }

    }

    logger.info("Mybatis Encrypt parameters Interceptor, method: {}, args: {}", methodName, invocation.getArgs()[1]);

  }

  //查詢結果解密處理

  privatevoiddealReturnValue(Object returnValue){

    if(returnValueinstanceofArrayList<?>){

      List<?> list = (ArrayList<?>)returnValue;

      for(Object val: list){

        if(valinstanceofPassenger){///

          //TODO

        }

        logger.info("Mybatis Decrypt result Interceptor, result object: {}", ToStringBuilder.reflectionToString(val));

      }

    }

  }

  @Override

  publicObject plugin(Object target) {

    returnPlugin.wrap(target,this);

  }

  @Override

  publicvoidsetProperties(Properties properties) {

  }

}

添加配置:

 代碼如下 復制代碼

<bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">

       <property name="typeAliasesPackage"value="com.xx.model"/>

       <property name="dataSource"ref="dataSource"/>

       <!-- 自動掃描mapping.xml文件 -->

       <property name="mapperLocations"value="classpath*:mybatis/*.xml"></property>

       <property name="plugins">

           <array>

              <beanclass="com.github.pagehelper.PageHelper">

                  <property name="properties">

                     <value>dialect=hsqldb</value>

                  </property>

              </bean>

              <beanclass="com.xx.interceptor.EncryptInterceptor">

                  <property name="properties">

                     <value>property-key=property-value</value>

                  </property>

              </bean>

           </array>

       </property>

    </bean>

copyright © 萬盛學電腦網 all rights reserved