Design Patterns Used in the MyBatis Framework
This article reviews the various design patterns—creational, structural, and behavioral—employed within MyBatis's source code, illustrating each pattern with diagrams and explaining their roles in simplifying factory creation, singleton configuration, builders, adapters, proxies, decorators, templates, strategies, and iterators.
Type: Creational Patterns
Factory Pattern
SqlSessionFactory's structure is shown in the diagram.
Factory Pattern: A simple factory is a creational pattern that provides a method in a parent class to create objects, allowing subclasses to decide the concrete type.
Scenario: SqlSessionFactory is a factory for obtaining sessions; each MyBatis operation opens a new session. The factory gathers data source configuration, builds a transaction factory, creates an executor for SQL operations, and finally returns a session implementation.
Related Designs: SqlSessionFactory, ObjectFactory, MapperProxyFactory, DataSourceFactory.
Singleton Pattern
Configuration singleton class structure is shown in the diagram.
Singleton Pattern: A creational pattern that guarantees a class has only one instance and provides a global access point.
Scenario: Configuration is a large singleton that spans the entire session lifecycle; all configuration objects (mappings, caches, parameters, interceptors, factories, etc.) are initialized within it and instantiated during the SqlSessionFactoryBuilder phase.
Related Scenarios: ErrorContext, LogFactory, Configuration.
Builder Pattern
ResultMap builder structure is shown in the diagram.
Builder Pattern: Constructs a complex object step by step from multiple simple objects, offering an optimal way to create objects.
Scenario: MyBatis uses many XxxBuilder classes to encapsulate XML parsing into various objects, keeping object‑property settings out of business logic and providing clear boundary isolation.
Related Scenarios: SqlSessionFactoryBuilder, XMLConfigBuilder, XMLMapperBuilder, XMLStatementBuilder, CacheBuilder.
Type: Structural Patterns
Adapter Pattern
Log implementation class structure is shown in the diagram.
Adapter Pattern: A structural pattern that enables objects with incompatible interfaces to work together.
Scenario: Numerous logging frameworks (Log4j, Log4j2, SLF4J, etc.) have different APIs; MyBatis defines a unified logging interface and adapts each framework to it.
Related Scenarios: Focused on log framework adaptation.
Proxy Pattern
Proxy pattern implementation structure is shown in the diagram.
Proxy Pattern: Provides a substitute or placeholder for another object, controlling access and allowing pre‑processing before delegating requests.
Scenario: MyBatis's MapperProxy implements DAO interfaces; the proxy handles method calls, delegates to the executor, and returns database results.
Related Scenarios: DriverProxy, Plugin, Invoker, MapperProxy.
Composite Pattern
Parse node class structure is shown in the diagram.
Composite Pattern: Allows objects to be composed into tree structures to represent part‑whole hierarchies.
Scenario: MyBatis XML dynamic SQL provides nine tags (trim, where, set, foreach, if, choose, when, otherwise, bind) that can be combined into complex SQL statements; each tag implements SqlNode, forming a rule tree.
Related Scenarios: Implementation of various SqlNode subclasses for SQL tag parsing.
Decorator Pattern
Second‑level cache decorator structure is shown in the diagram.
Decorator Pattern: Wraps an object with a special container that adds new behavior.
Scenario: MyBatis's second‑level cache decorates the simple executor, adding caching behavior on top of the basic execution flow.
Type: Behavioral Patterns
Template Method Pattern
SQL execution template structure is shown in the diagram.
Template Method Pattern: Defines the skeleton of an algorithm in a superclass while allowing subclasses to override specific steps without changing the overall structure.
Scenario: BaseExecutor defines a standard workflow for query and update operations; subclasses like SimpleExecutor implement the concrete steps.
Related Scenarios: BaseExecutor, SimpleExecutor, BaseTypeHandler.
Strategy Pattern
Multi‑type handler strategy structure is shown in the diagram.
Strategy Pattern: Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Scenario: MyBatis uses TypeHandler implementations to handle different Java types when retrieving JDBC results, avoiding large if‑else blocks.
Related Scenarios: PooledDataSource, UnpooledDataSource, BatchExecutor, ReuseExecutor, SimpleExecutor, CachingExecutor, LongTypeHandler, StringTypeHandler, DateTypeHandler.
Iterator Pattern
Field parsing implementation structure is shown in the diagram.
Iterator Pattern: Allows traversal of a collection without exposing its underlying representation.
Scenario: PropertyTokenizer parses object property strings for MyBatis's MetaObject, used extensively for configuration and parameter handling.
Related Scenarios: PropertyTokenizer.
Summary
Through this review, about ten design patterns are identified in MyBatis, demonstrating how a complex ORM framework leverages patterns to solve intricate problems.
When tackling complex scenarios, one should decompose problems, apply appropriate design patterns and principles, and gradually build a deeper understanding of architectural solutions.
Studying source code goes beyond interview preparation; it enriches one’s grasp of sophisticated design techniques, expands coding mindset, and accumulates practical experience, paving the way to become a senior engineer or architect.
Final Note (Please Follow)
If this article helped you, please like, view, share, and bookmark; your support motivates the author to continue producing content.
Additional resources and paid knowledge community are available via the provided links.
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.