What 10+ Design Patterns Power MyBatis’s 20k+ Lines of Code?
The article examines how MyBatis’s massive source code employs more than ten classic design patterns—creational, structural, and behavioral—to decouple complex scenarios, illustrating each pattern with diagrams, typical use‑cases, and related classes within the framework.
Creational Patterns
Factory Pattern
Definition: Provides a method in a super‑type that creates concrete objects, allowing subclasses to decide which implementation to instantiate.
MyBatis usage: SqlSessionFactoryBuilder builds a SqlSessionFactory. The factory hides the creation of the data‑source, transaction factory and executor. When a session is requested, the factory assembles these components and returns a SqlSession implementation.
Key classes: SqlSessionFactory, ObjectFactory, MapperProxyFactory, DataSourceFactory.
Singleton Pattern
Definition: Guarantees a class has exactly one instance and provides a global access point.
MyBatis usage: The Configuration object is a large singleton that lives for the entire lifecycle of a SqlSessionFactory. All mappings, caches, interceptors, type handlers and factories are stored inside this single instance, which is created by SqlSessionFactoryBuilder during start‑up.
Key classes: Configuration, ErrorContext, LogFactory.
Builder Pattern
Definition: Constructs a complex object step‑by‑step using simpler components, separating construction from representation.
MyBatis usage: Numerous *Builder classes parse XML configuration files and assemble the corresponding runtime objects. For example, XMLConfigBuilder reads mybatis-config.xml and creates a Configuration; XMLMapperBuilder parses mapper XML files into MappedStatement objects; CacheBuilder builds cache instances. The builders hide the intricate parsing logic from the rest of the framework.
Key classes: SqlSessionFactoryBuilder, XMLConfigBuilder, XMLMapperBuilder, XMLStatementBuilder, CacheBuilder.
Structural Patterns
Adapter Pattern
Definition: Allows objects with incompatible interfaces to collaborate by translating one interface into another.
MyBatis usage: MyBatis defines its own Log interface and provides adapters for Log4j, Log4j2 and SLF4J. This enables the framework to use any of the supported logging libraries without coupling to a specific API.
Key classes: LogImplLog4j, LogImplLog4j2, LogImplSlf4j (adapter implementations).
Proxy Pattern
Definition: Provides a surrogate object that controls access to a real subject, allowing pre‑processing or lazy loading.
MyBatis usage: MapperProxy implements DAO interfaces at runtime. When a mapper method is invoked, the proxy intercepts the call, looks up the corresponding MappedStatement, delegates execution to an Executor, and returns the result. This decouples the user‑defined mapper interface from the actual SQL execution logic.
Key classes: MapperProxy, MapperProxyFactory, Plugin, Invoker, DriverProxy.
Composite Pattern
Definition: Represents part‑whole hierarchies as tree structures where individual objects and compositions are treated uniformly.
MyBatis usage: Dynamic SQL tags ( trim, where, set, foreach, if, choose, when, otherwise, bind) are parsed into implementations of the SqlNode interface. These nodes are assembled into a tree that is later evaluated to produce the final SQL string.
Key classes: Various SqlNode implementations such as TrimSqlNode, WhereSqlNode, IfSqlNode, etc.
Decorator Pattern
Definition: Adds responsibilities to an object dynamically by wrapping it in a decorator that conforms to the same interface.
MyBatis usage: The second‑level cache is implemented by wrapping a SimpleExecutor with a CacheExecutor. The decorator forwards calls to the underlying executor while adding cache‑lookup and cache‑update behavior.
Key classes: CacheExecutor, SimpleExecutor.
Behavioral Patterns
Template Method Pattern
Definition: Defines the skeleton of an algorithm in an abstract class, allowing subclasses to override specific steps without changing the overall structure.
MyBatis usage: BaseExecutor defines the workflow for query and update operations (open session, prepare statement, execute, handle results, close). Subclasses such as SimpleExecutor, BatchExecutor, CachingExecutor implement the concrete steps (e.g., how statements are cached or batched).
Key classes: BaseExecutor, SimpleExecutor, CachingExecutor, BaseTypeHandler.
Strategy Pattern
Definition: Defines a family of interchangeable algorithms, encapsulating each one in a separate class.
MyBatis usage: The TypeHandler interface abstracts the conversion between JDBC types and Java types. Implementations such as LongTypeHandler, StringTypeHandler, DateTypeHandler provide the concrete conversion logic, allowing the framework to select the appropriate handler at runtime without large conditional blocks.
Key classes: TypeHandler, LongTypeHandler, StringTypeHandler, DateTypeHandler, plus data‑source implementations ( PooledDataSource, UnpooledDataSource) and executor strategies ( BatchExecutor, ReuseExecutor, SimpleExecutor, CachingExecutor).
Iterator Pattern
Definition: Provides a way to sequentially access elements of a collection without exposing its underlying representation.
MyBatis usage: PropertyTokenizer parses a dotted property expression (e.g., user.address.street) into tokens that can be iterated over. The iterator is used by MetaObject to navigate nested objects during data binding and result mapping.
Key class: PropertyTokenizer.
Overall Observation
Analyzing the MyBatis source code (≈20 000 lines) reveals the systematic application of roughly ten classic design patterns across creational, structural and behavioral categories. These patterns enable the framework to achieve high decoupling, extensibility, and maintainability, and they serve as concrete examples of how large‑scale ORM systems are architected.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.
