Comprehensive Guide to MyBatis: Concepts, Configuration, SQL Mapping, and Dynamic SQL
This article provides a thorough overview of MyBatis, covering its core concepts, architecture, Spring integration, configuration elements, SQL mapping techniques, dynamic SQL tags, and practical usage tips such as type aliases, ResultMap, caching, and the differences between #{} and ${} placeholders.
MyBatis is a lightweight SQL mapping framework that simplifies ORM tasks while offering a rich set of features for Java applications.
1. Core Concepts
MyBatis operates on top of JDBC, using SqlSession to manage database connections and caching. The main components include SqlSessionFactoryBuilder , SqlSessionFactory , SqlSession , and mapper interfaces, each with distinct lifecycles.
When used in a Spring environment, Spring discovers the MyBatis configuration file, creates a SqlSessionFactory , injects mapper beans, and scans classpath for mapper XML files, linking them to their interfaces.
2. What MyBatis Contains
MyBatis provides two essential parts: core configuration (caching, data source, logging, etc.) and mapper interface mappings that define SQL statements for business logic.
3. SQL Mapping
Mappings can be defined via XML or annotations. Common tags include select , insert , update , delete , and the reusable <sql> fragment.
Example of a reusable SQL fragment:
<sql id="baseColumns">id, name, age</sql>
The placeholder syntax differs: #{} uses prepared‑statement parameters (safer and faster), while ${} performs direct string substitution.
Type aliases reduce verbosity, e.g., <typeAlias type="com.someapp.model.User" alias="User"/> .
ResultMap is a powerful feature that maps result sets to complex object graphs, handling nested queries and collections.
Caching can be enabled with the cache tag for second‑level cache, and cache-ref allows sharing caches between namespaces.
4. Dynamic SQL
MyBatis supports dynamic SQL tags such as:
if – conditional inclusion based on a test expression.
choose (with when and otherwise ) – mutually exclusive branches.
trim (with where and set ) – automatically adds/removes leading/trailing keywords and commas.
foreach – iterates over collections, arrays, or maps to generate repeated SQL fragments.
bind – defines a variable using an OGNL expression for later use in the statement.
These dynamic tags enable flexible, maintainable SQL generation within MyBatis mapper files.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.