Unlocking MyBatis: 10 Design Patterns Powering Its Architecture

The article examines how MyBatis leverages around ten classic design patterns—grouped into Creational, Structural, and Behavioral categories—to decouple complex ORM logic, describing each pattern’s role, typical usage scenarios, and related components within the framework.

Architect
Architect
Architect
Unlocking MyBatis: 10 Design Patterns Powering Its Architecture

MyBatis’s source code of over 20,000 lines heavily employs design patterns to decouple complex scenarios in its architecture. This article enumerates the main patterns used, grouped by Creational, Structural, and Behavioral categories, and explains their purpose, typical usage in MyBatis, and related components.

Creational Patterns

Factory Pattern

Definition: Simple factory provides a method in a superclass to create objects, allowing subclasses to decide the concrete type.

Scenario in MyBatis: SqlSessionFactory is the factory that creates a new session for each database operation. It gathers data source configuration, builds a transaction factory, creates an executor for SQL, and finally returns a session implementation.

Related components: SqlSessionFactory, ObjectFactory, MapperProxyFactory, DataSourceFactory.

Singleton Pattern

Definition: Guarantees a class has only one instance and provides a global access point.

Scenario in MyBatis: Configuration is a large singleton that lives throughout the session lifecycle. All configuration objects (mappers, caches, type handlers, plugins, etc.) are initialized inside it, and it is instantiated during the SqlSessionFactoryBuilder build phase.

Related components: ErrorContext, LogFactory, Configuration.

Builder Pattern

Definition: Constructs a complex object step‑by‑step using multiple simple objects, providing a clear creation process.

Scenario in MyBatis: Numerous *Builder classes (e.g., XmlConfigBuilder, ResultMapBuilder) parse XML files into object graphs. Builders and their assistants encapsulate object creation, keeping configuration logic separate from business flow.

Related components: SqlSessionFactoryBuilder, XMLConfigBuilder, XMLMapperBuilder, XMLStatementBuilder, CacheBuilder.

Structural Patterns

Adapter Pattern

Definition: Allows incompatible interfaces to work together.

Scenario in MyBatis: MyBatis defines a unified logging interface to adapt various logging frameworks (Log4j, Log4j2, SLF4J), enabling interchangeable use without changing MyBatis core code.

Related components: Logging adapters for different log frameworks.

Proxy Pattern

Definition: Provides a placeholder or surrogate for another object, controlling access and allowing pre‑processing.

Scenario in MyBatis: MapperProxy implements DAO interfaces. The proxy intercepts method calls, delegates to the executor, and returns database results, effectively supplying concrete implementations for mapper interfaces.

Related components: DriverProxy, Plugin, Invoker, MapperProxy.

Composite Pattern

Definition: Organizes objects into tree structures to represent part‑whole hierarchies.

Scenario in MyBatis: The dynamic SQL XML tags ( trim, where, set, foreach, if, choose, when, otherwise, bind) are combined into a SqlNode tree, where each node implements the SqlNode interface, forming a composite structure.

Related components: Various SqlNode implementations for each XML tag.

Decorator Pattern

Definition: Wraps an object with additional behavior without altering its interface.

Scenario in MyBatis: The second‑level cache decorates the simple executor. A cache executor wraps the simple executor to add caching logic, effectively applying the decorator (also known as the Russian‑doll) pattern.

Related components: SimpleExecutor, cache executor, first‑level and second‑level cache implementations.

Behavioral Patterns

Template Method Pattern

Definition: Defines the skeleton of an algorithm in a superclass while allowing subclasses to override specific steps.

Scenario in MyBatis: BaseExecutor provides a template for query and update operations. Subclasses like SimpleExecutor and CachingExecutor implement the variable steps while reusing the common workflow.

Related components: BaseExecutor, SimpleExecutor, BaseTypeHandler.

Strategy Pattern

Definition: Defines a family of algorithms, encapsulates each one, and makes them interchangeable.

Scenario in MyBatis: Different TypeHandler implementations handle various Java‑to‑JDBC type conversions, avoiding large if blocks and allowing easy substitution of conversion strategies.

Related components: PooledDataSource, UnpooledDataSource, BatchExecutor, ReuseExecutor, LongTypeHandler, StringTypeHandler, DateTypeHandler.

Iterator Pattern

Definition: Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

Scenario in MyBatis: PropertyTokenizer iterates over property strings to parse nested property paths for MetaObject reflection, used extensively in configuration and parameter handling.

Related components: PropertyTokenizer.

Conclusion

By cataloguing roughly ten design patterns used throughout MyBatis, we see that a sophisticated ORM framework relies heavily on classic patterns to solve complex architectural problems. Understanding these patterns deepens one’s grasp of software design, improves code readability, and equips engineers to tackle similar challenges in other projects.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsJavaBackend DevelopmentMyBatis
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.