Master MyBatis: Core Principles, Architecture, and Interview Tips
This article provides a comprehensive overview of MyBatis, covering its definition as a semi‑ORM persistence framework, core architecture, key components, advantages and drawbacks, practical usage patterns, and a collection of common interview questions with detailed answers for Java developers.
What is MyBatis?
MyBatis is a powerful persistence framework for Java that supports custom SQL, stored procedures, and advanced mapping. It is a semi‑ORM tool that wraps JDBC, allowing developers to focus on SQL statements while handling connection, statement creation, and result mapping automatically.
Advantages
SQL‑centric programming offers high flexibility and performance control.
Reduces JDBC boilerplate by over 50%.
Compatible with any JDBC‑supported database.
Integrates smoothly with Spring.
Provides mapping tags for object‑relational relationships.
Disadvantages
Requires manual SQL writing, demanding strong SQL skills.
SQL is database‑specific, limiting portability.
Suitable Scenarios
MyBatis is ideal for projects that need fine‑grained SQL control, high performance, or frequent requirement changes, such as many internet applications.
Architecture Overview
The initialization starts from mybatis‑config.xml, which is parsed into a Configuration object.
Key steps include:
Loading configuration from XML files and annotations into MappedStatement objects.
SQL parsing: locating the MappedStatement by ID and generating the final SQL with parameters.
SQL execution: sending the SQL to the database.
Result mapping: converting the result set into Java objects such as HashMap, POJOs, or primitive types.
Three‑Layer Architecture
API Interface Layer – Exposes methods for external callers and forwards requests to the data‑processing layer.
Data Processing Layer – Handles SQL lookup, parsing, execution, and result mapping.
Foundation Layer – Provides core services like connection management, transaction handling, configuration loading, and caching.
Core Components
SqlSessionFactoryBuilder
Creates a Configuration from XML or programmatic settings and builds a SqlSessionFactory.
SqlSessionFactory
Singleton‑style factory that produces SqlSession instances; each factory corresponds to one environment configuration.
SqlSession
Top‑level API for database interaction; obtains MappedStatement by ID and executes CRUD operations. It is not thread‑safe and should be closed after use.
Executor
Core of MyBatis execution. Implementations include SimpleExecutor, ReuseExecutor, and BatchExecutor, handling statement creation, caching, and batch processing.
StatementHandler
Wraps JDBC Statement operations, sets parameters, and converts results to Java collections.
ResultSetHandler
ParameterHandler – converts method arguments to JDBC parameters.
ResultSetHandler – transforms ResultSet into Java collections.
TypeHandler – maps between Java types and JDBC types.
MappedStatement
Holds mapping information for a single SQL node, including the SQL string, input and output parameter mappings.
SqlSource
Generates dynamic SQL based on the provided parameter object and produces a BoundSql instance.
Common Interview Questions
JDBC steps: load driver, obtain connection, create statement, execute CRUD, retrieve results, close resources.
Difference between #{} and ${}: #{} uses prepared‑statement placeholders (prevents SQL injection), while ${} performs direct string replacement.
How MyBatis implements pagination: RowBounds for in‑memory pagination or physical pagination via SQL or plugins.
How to write a MyBatis plugin: implement Interceptor, override intercept(), annotate with @Intercepts, and configure in mybatis‑config.xml.
Dynamic SQL tags: trim, where, set, foreach, if, choose, when, otherwise, bind.
Mapping XML tags: <resultMap>, <parameterMap>, <sql>, <include>, <selectKey>, plus the standard CRUD tags.
First‑ and second‑level cache behavior and configuration.
Sample Batch Insert with Generated Keys
<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
insert into Author(username, password, email, bio) values
<foreach item="item" collection="list" separator=",">
(#{item.username}, #{item.password}, #{item.email}, #{item.bio})
</foreach>
</insert>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Intelligent Backend & Architecture
We share personal insights on intelligent, automated backend technologies, along with practical AI knowledge, algorithms, and architecture design, grounded in real business scenarios.
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.
