You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.2 KiB

  1. package com.iformall.plugin;
  2. import org.apache.ibatis.executor.statement.StatementHandler;
  3. import org.apache.ibatis.plugin.*;
  4. import org.apache.ibatis.session.ResultHandler;
  5. import com.iformall.plugin.entity.ChainValue;
  6. import java.sql.Connection;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. /**
  12. *共享数据库的多租户系统实现
  13. * Created by Stormeye on 2018/10/22.
  14. */
  15. @Intercepts({
  16. //@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
  17. //@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
  18. @Signature( method = "prepare", type = StatementHandler.class,args = {Connection.class, Integer.class}),
  19. @Signature(method = "query", type = StatementHandler.class, args = {java.sql.Statement.class, ResultHandler.class})
  20. })
  21. public class MyBatisItercepters implements Interceptor {
  22. private List<MyBatisPlus> plugins;
  23. public MyBatisItercepters(){
  24. }
  25. public void setPlugins(List<MyBatisPlus> plugins) {
  26. this.plugins = plugins;
  27. }
  28. public Object intercept(Invocation invocation) throws Throwable {
  29. if (null != plugins && plugins.size() > 0 ) {
  30. // 能从cookie或者session获取到tenantId
  31. Map<String,ChainValue> chainValues = new HashMap<String,ChainValue>();
  32. for (int i = 0 ; i < plugins.size() ; i++) {
  33. MyBatisPlus plug = plugins.get(i);
  34. invokeIntercept(plug, invocation, chainValues);
  35. }
  36. }
  37. return invocation.proceed();
  38. }
  39. private void invokeIntercept(MyBatisPlus plug,Invocation invocation,Map<String,ChainValue> chainMap) throws Throwable {
  40. Map<String,ChainValue> resultMap = plug.intercept(invocation, chainMap);
  41. if (null != resultMap) {
  42. chainMap.putAll(resultMap);
  43. }
  44. }
  45. /**
  46. * 生成代理对象
  47. *
  48. * @param target
  49. * @return
  50. */
  51. @Override
  52. public Object plugin(Object target) {
  53. if (target instanceof StatementHandler) {
  54. return Plugin.wrap(target, this);
  55. } else {
  56. return target;
  57. }
  58. }
  59. }