NOTE

Introduction

Why MyBatis exists and its execution flow

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

Why MyBatis

  • JDBC

SQL is written directly in Java code, which causes severe hard-coding.

  • Hibernate

A complete ORM that operates on the database in an object-oriented way.

However, it is not flexible enough.

  • MyBatis

You can write code manually while putting SQL in configuration files.

Flow

  1. MyBatis configuration

SqlMapConfig.xml is MyBatis’s global configuration file and configures information such as the MyBatis runtime environment.

The mapper.xml file is the SQL-mapping file. SQL statements that operate on the database are configured in this file. This file needs to be loaded from SqlMapConfig.xml.

  1. Build the SqlSessionFactory, the session factory, from MyBatis environment and other configuration information.

  2. The session factory creates a SqlSession. Database operations need to go through the SqlSession.

  3. At the bottom layer, MyBatis defines an Executor interface for operating on the database. The Executor interface has two implementations: a basic executor and a caching executor.

  4. MappedStatement is also a low-level MyBatis wrapper object. It wraps MyBatis configuration information and SQL-mapping information. One SQL statement in a mapper.xml file corresponds to one MappedStatement object, and the SQL id is the id of the MappedStatement.

  5. MappedStatement defines the input parameters for SQL execution, including HashMap, primitive types, and POJOs. Before executing SQL, Executor maps the input Java object into the SQL through MappedStatement. This input-parameter mapping is equivalent to setting parameters on a PreparedStatement in JDBC programming.

  6. MappedStatement defines the output result of SQL execution, including HashMap, primitive types, and POJOs. After executing SQL, Executor maps the output result to Java objects through MappedStatement. This output-result mapping process is equivalent to parsing and processing the result set in JDBC programming.

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub