mybatis与设计模式

一、工厂方法模式

1.SqlSessionFactory

简单的代码如下

public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SqlSession openSession() {
        // 这一步实际上还会初始化mybatis的Executor和事务
        return new DefaultSqlSession(configuration, new SimpleExecutor());
    }
}
public class Main {
    public static void main(String[] args) {
        String resource = "/mybatis-config.xml";
        InputStream inputStream = com.zhuo.pattern.builder.Main.class.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
    }
}
工厂方法模式让调用者不需要知道SqlSession具体实例了是哪个类。当需要修改SqlSession实例对象的时候,调用方不需要做任何改动,甚至丝毫没有感知到逻辑做了变更。

二、建造者模式

1.SqlSessionFactoryBuilder

简单化的代码:

public class SqlSessionFactoryBuilder {
    public SqlSessionFactory build(InputStream inputStream){
        return build(inputStream, null, null);
    }
    public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
        try {
            // 加载XML的配置文件
            XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
            return build(parser.parse());
        } catch (Exception e) {
            throw new RuntimeException("Error building SqlSession.", e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Intentionally ignore. Prefer previous error.
            }
        }
    }
    public SqlSessionFactory build(Configuration config) {
        return new DefaultSqlSessionFactory(config);
    }
}

建造对象前需要要做一些前置操作来达成创建实例的作用。此处先加载了xml文件的一些数据后再去创建DefaultSqlSessionFactory实例。

三、动态代理——mybatis的核心

简单化的代码

public class Main {
    public static void main(String[] args) {
        SqlSession sqlSession = new DefaultSqlSession(new Configuration(), new SimpleExecutor());
        TestMapper mapper = sqlSession.getMapper(TestMapper.class);
        String result = mapper.selectTest();
        System.out.println(result);
    }
}

mapper

public interface TestMapper {
    @Select("随便写一个sql")
    String selectTest();
}
/**
 * @description: 默认sql会话
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> clazz) {
        MapperProxy mapperProxy = new MapperProxy(this);
        // 通过动态代理获取对应的代理Mapper
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, mapperProxy);
    }

    @Override
    public <T> T selectList(String statement, Object parameter) {
        MappedStatement ms = configuration.getMappedStatement(statement);
        return (T) executor.query(ms, parameter);
    }
}
/**
 * @description: mapper代理类
 */
public class MapperProxy implements InvocationHandler {

    private SqlSession sqlSession;

    public MapperProxy(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    private static final Set<Class<? extends Annotation>> SQL_ANNOTATION_TYPES = new HashSet<>();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    	// 代理Mapper调用具体的方法实际上是进入到这里了
        return execute(method, sqlSession);
    }

    private Object execute(Method method, SqlSession sqlSession) {
        SqlCommandType sqlCommandType = getSqlCommandType(method);
        Object result;
        // 根据不同的类型调用不同的执行器
        switch (sqlCommandType) {
            case INSERT: {
                result = "插入数据";
                break;
            }
            case UPDATE: {
                result = "更新数据";
                break;
            }
            case DELETE: {
                result = "删除数据";
                break;
            }
            case SELECT:
                result = "查询数据";
                // 通过反射从注解和参数解析出来的参数
                final Map<String, Object> param = new HashMap<>(0);
                // String statementId = mapperInterface.getName() + "." + methodName;
                // 这里的话其实select是有很多情况的,这里随便写一下
                result = "查询数据" + sqlSession.selectList("事先加载好的statement存放在Map中的id", param)
                                            .toString();
                break;
            default:
                throw new RuntimeException("Unknown execution method for: " + sqlCommandType);
        }
        return result;
    }

	/**
	 * 获取注解类型:@Select、@Insert、@Update、@Delete中哪一种
	 */
    private SqlCommandType getSqlCommandType(Method method) {
        Class<? extends Annotation> type = getSqlAnnotationType(method);

        if (type == null) {
            return SqlCommandType.UNKNOWN;
        }

        return SqlCommandType.valueOf(type.getSimpleName()
                                          .toUpperCase(Locale.ENGLISH));
    }

    private Class<? extends Annotation> getSqlAnnotationType(Method method) {
        for (Class<? extends Annotation> type : SQL_ANNOTATION_TYPES) {
            Annotation annotation = method.getAnnotation(type);
            if (annotation != null) {
                return type;
            }
        }
        return null;
    }

    static {
        SQL_ANNOTATION_TYPES.add(Select.class);
        SQL_ANNOTATION_TYPES.add(Insert.class);
        SQL_ANNOTATION_TYPES.add(Update.class);
        SQL_ANNOTATION_TYPES.add(Delete.class);
    }
}

上述代码省去了解析sql、解析参数、执行sql(JDBC)和sql执行结果匹配返回值等的操作。通过代理模式,我们很明显的感受到原先写的JDBC代码被封装了起来,由代理类去执行。我们这边只需要写一个sql加注解就能自动的帮我们执行JDBC的代码。

四、适配器模式

简化后的代码

public class Main {
    public static void main(String[] args) {
        logFactoryDemo();
    }
    private static void logFactoryDemo() {
        Log log = LogFactory.getLog(com.zhuo.pattern.factory.Main.class);
        log.debug("hello,log");
    }
}
public final class LogFactory {

    /**
     * Marker to be used by logging implementations that support markers
     */
    public static final String MARKER = "MYBATIS";
    private static Constructor<? extends Log> logConstructor;
    static {
        // 尝试加载这些日志,按照加载的顺序排优先级
        tryImplementation(LogFactory::useSlf4jLogging);
        tryImplementation(LogFactory::useCommonsLogging);
        tryImplementation(LogFactory::useLog4J2Logging);
        tryImplementation(LogFactory::useLog4JLogging);
        tryImplementation(LogFactory::useJdkLogging);
        tryImplementation(LogFactory::useNoLogging);
    }
    private LogFactory() {
        // disable construction
    }
    public static Log getLog(Class<?> aClass) {
        return getLog(aClass.getName());
    }
    public static Log getLog(String logger) {
        try {
            return logConstructor.newInstance(logger);
        } catch (Throwable t) {
            throw new RuntimeException("Error creating logger for logger " + logger + ".  Cause: " + t, t);
        }
    }
    public static synchronized void useCustomLogging(Class<? extends Log> clazz) {
        setImplementation(clazz);
    }
    public static synchronized void useSlf4jLogging() {
        setImplementation(com.zhuo.mybatis.logging.stdout.StdOutImpl.class);
    }
    public static synchronized void useCommonsLogging() {
        setImplementation(com.zhuo.mybatis.logging.stdout.StdOutImpl.class);
    }
    public static synchronized void useLog4JLogging() {
        setImplementation(com.zhuo.mybatis.logging.stdout.StdOutImpl.class);
    }
    public static synchronized void useLog4J2Logging() {
        setImplementation(com.zhuo.mybatis.logging.stdout.StdOutImpl.class);
    }
    public static synchronized void useJdkLogging() {
        setImplementation(com.zhuo.mybatis.logging.stdout.StdOutImpl.class);
    }
    public static synchronized void useStdOutLogging() {
        setImplementation(com.zhuo.mybatis.logging.stdout.StdOutImpl.class);
    }
    public static synchronized void useNoLogging() {
        setImplementation(com.zhuo.mybatis.logging.stdout.StdOutImpl.class);
    }
    private static void tryImplementation(Runnable runnable) {
        if (logConstructor == null) {
            try {
                runnable.run();
            } catch (Throwable t) {
                // ignore
            }
        }
    }
    private static void setImplementation(Class<? extends Log> implClass) {
        try {
            Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
            Log log = candidate.newInstance(LogFactory.class.getName());
            if (log.isDebugEnabled()) {
                log.debug("Logging initialized using '" + implClass + "' adapter.");
            }
            logConstructor = candidate;
        } catch (Throwable t) {
            throw new RuntimeException("Error setting Log implementation.  Cause: " + t, t);
        }
    }
}

根据系统拥有的日志框架去按顺序加载不同的日志框架作为mybatis的日志打印的框架

五、单例模式——在单个线程内单例

public class Main {
    public static void main(String[] args) {

        // 线程内单例
        ErrorContext instance1 = ErrorContext.instance();
        ErrorContext instance2 = ErrorContext.instance();
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
        new Thread(()-> System.out.println(ErrorContext.instance().hashCode())).start();
        new Thread(()-> System.out.println(ErrorContext.instance().hashCode())).start();
    }

}
/**
 * @description: 线程错误信息
 */
public class ErrorContext {

    private static final String LINE_SEPARATOR = System.getProperty("line.separator","\n");
    private static final ThreadLocal<ErrorContext> LOCAL = new ThreadLocal<>();

    private ErrorContext stored;
    private String resource;
    private String activity;
    private String object;
    private String message;
    private String sql;
    private Throwable cause;

    private ErrorContext() {
    }
    
    public static ErrorContext instance() {
        ErrorContext context = LOCAL.get();
        if (context == null) {
            context = new ErrorContext();
            LOCAL.set(context);
        }
        return context;
    }
    // ...
}

使用了ThreadLocal,来保证这个对象是线程内使用的,且在这个线程内只创建一次对象(单例)

六、模版方法模式

public class Main {
    public static void main(String[] args) {
        SqlSession sqlSession = new DefaultSqlSession(new Configuration(), new SimpleExecutor());
        TestMapper mapper = sqlSession.getMapper(TestMapper.class);
        String result = mapper.selectTest();
        System.out.println(result);

        SqlSession sqlSession2 = new DefaultSqlSession(new Configuration(), new BatchExecutor());
        TestMapper mapper2 = sqlSession2.getMapper(TestMapper.class);
        String result2 = mapper2.selectTest();
        System.out.println(result2);
    }
}
/**
 * @description: 模版的简单实例
 */
public class SimpleExecutor extends BaseExecutor {
    @Override
    protected <E> List<E> doQuery(MappedStatement ms, Object parameter) {
        return (List<E>) Collections.singletonList("jdbc查数据库");
    }
}
/**
 * @description: 模版的批量实例
 */
public class BatchExecutor extends BaseExecutor {
    @Override
    protected <E> List<E> doQuery(MappedStatement ms, Object parameter) {
        return (List<E>) Collections.singletonList("jdbc批量操作数据库");
    }
}
public abstract class BaseExecutor implements Executor {
    @Override
    public <E> List<E> query(MappedStatement ms, Object parameter) {
        // 如果指定了缓存,读取缓存
        List<E> list = null;
        // 省略有缓存的操作
        if (list == null) {
            list = queryFromDatabase(ms, parameter);
        }
        return list;
    }

    private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter) {
        return doQuery(ms, parameter);
    }

    protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter);
}

在前面已经写到过sqlSession生成代理Mapper的代码,调用mapper.selectTest()实际上进入到MapperProxy的invoke方法,invoke方法中又调用了execute方法,execute方法的查询部分又调用了sqlSession.selectList。而这个方法内部又是调用了BaseExecutor的query方法。这个方法内部的实现是判断是否要查缓存后再做具体的操作(是批量操作数据库还是简单的操作数据库)。可以知道是否要查询缓存的操作是两个子类共有的代码。于是将这部分的代码给抽出到父类中,这就是模版,然后再具体调用到实现的子类重写的方法去(doQuery)。模版方法可以大大的提高代码的重用性,外部调用为直接调用父类的方法后,再由父类去调用子类也符合开放封闭原则。

七、责任链模式——扩展mybatis的功能(mybati高级功能)

这里写的是链条的接口,实现这个链条就能对mybatis的功能进行扩展()

public interface Interceptor {
  Object intercept(Invocation invocation) throws Throwable;
  Object plugin(Object target);
  void setProperties(Properties properties);
}

pluginAll的方法给mybatis需要扩展的地方使用,mybatis可扩展的一共是四个,分别是:Executor、ParameterHandler、StatementHandler、ResultSetHandler,然后去触发调用执行plugin的具体内容

public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
  // target就是上述的四个对象
  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }
  
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}

链条的plugin会调用到Plugin.wrap方法,然后再通过代理的方式对上面的四个对象进行特殊的处理后再返回

public class Plugin implements InvocationHandler {

  private final Object target;
  private final Interceptor interceptor;
  private final Map<Class<?>, Set<Method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.get(sig.type());
      if (methods == null) {
        methods = new HashSet<Method>();
        signatureMap.put(sig.type(), methods);
      }
      try {
        Method method = sig.type().getMethod(sig.method(), sig.args());
        methods.add(method);
      } catch (NoSuchMethodException e) {
        throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
  }

  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    while (type != null) {
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值