Deep Dive into MyBatis: Architecture, Configuration Parsing, Proxy Creation, and SQL Execution
This article provides a comprehensive, step‑by‑step analysis of MyBatis, covering its core features, three‑layer architecture, configuration file parsing, dynamic proxy generation, and the detailed process of executing SQL statements within the framework.
The article introduces MyBatis as a lightweight, stable ORM framework for Java that maps objects to relational databases, highlighting its main capabilities such as SQL mapping configuration, dynamic SQL, parameter mapping, result set mapping, transaction management, connection‑pool integration, and second‑level caching.
It explains that MyBatis’s architecture consists of three layers—foundation support, core processing, and interface layer—and outlines the overall workflow: defining interfaces and XML/annotation configurations, loading and parsing configuration files, generating mapper proxies via SqlSession.getMapper, and finally executing SQL.
During configuration parsing, MyBatis loads the main mybatis-config.xml file into a Configuration object, uses XMLConfigBuilder for global settings, XMLMapperBuilder for mapper files, and XMLStatementBuilder for individual SQL statements.
Proxy construction involves MapperProxyFactory, MapperRegistry, and MapperProxy, leveraging JDK dynamic proxies to create concrete implementations of mapper interfaces.
The SQL execution phase relies on standard JDBC operations: creating Statement / PreparedStatement / CallableStatement, executing queries, handling ResultSet, and mapping results back to Java objects. MyBatis supports various execution methods such as selectOne(), selectList(), insert(), update(), and delete().
Key code example for initializing MyBatis:
// <1> Load configuration file
InputStream is = Resources.getResourceAsStream("mybatis.xml");
// <2> Build SqlSessionFactory
sessionFactory = new SqlSessionFactoryBuilder().build(is);
// <3> Open SqlSession
SqlSession session = factory.openSqlSession();
// <4> Get mapper proxy
UserMapper mapper = session.getMapper(UserMapper.class);
// ... invoke mapper methodsFinally, the article summarizes the complete MyBatis workflow: creating a SqlSessionFactory, opening a SqlSession, executing SQL via mapper methods, parsing SQL (including dynamic SQL and parameter/result mapping), sending the statement to the database, and mapping the results back to Java objects.
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.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
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.
