MyBatis is an excellent persistence layer framework that associates SQL statements with Java objects through mapping files (Mapper XML files) or annotations. This article will introduce the Result Mapping mechanism of MyBatis in detail to help you understand and apply this powerful feature, improve development efficiency and maintainability of your code.
1. What is result mapping
In MyBatis, a result mapping refers to mapping column values from the SQL query result set to properties of a Java object. By configuring result mapping, complex query results can be easily converted into easy-to-operate Java objects.
2. Basic result mapping
MyBatis provides two main ways to map results: through XML configuration files and annotations. The following is a detailed introduction to these two methods.
2.1 Result Mapping via XML Configuration Files
Suppose there is oneUser
kind:
public class User { private int id; private String name; private String email; // getters and setters }
The corresponding database table structure is as follows:
CREATE TABLE users ( id INT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50) );
First, in MyBatis mapping files (such asSQL query and result mapping are defined in ):
<mapper namespace=""> <select resultType=""> SELECT id, name, email FROM users WHERE id = #{id} </select> </mapper>
Here,resultType
The attribute specifies the Java class to which the query result will map. MyBatis will automatically name the column name of the query result andUser
Map the attribute names of the class.
2.2 Result mapping through annotations
MyBatis also supports the use of annotations to configure SQL queries and result mappings:
import ; public interface UserMapper { @Select("SELECT id, name, email FROM users WHERE id = #{id}") User getUserById(int id); }
3. Complex result mapping
In practical applications, query results are often not just simple flat data, but may also contain nested objects or collections. At this time, a more complex result mapping configuration is needed.
3.1 Nested Object Mapping
Suppose there is oneOrder
class, which contains oneUser
Object:
public class Order { private int id; private User user; private Date orderDate; // getters and setters }
The corresponding database table structure is as follows:
CREATE TABLE orders ( id INT PRIMARY KEY, user_id INT, order_date DATE, FOREIGN KEY (user_id) REFERENCES users(id) );
Configure nested object mapping in MyBatis' mapping file:
<mapper namespace=""> <resultMap type=""> <id property="id" column="id" /> <result property="orderDate" column="order_date" /> <association property="user" javaType=""> <id property="id" column="user_id" /> <result property="name" column="user_name" /> <result property="email" column="user_email" /> </association> </resultMap> <select resultMap="OrderResultMap"> SELECT , o.order_date, AS user_id, AS user_name, AS user_email FROM orders o JOIN users u ON o.user_id = WHERE = #{id} </select> </mapper>
Here,association
Elements are used to define and nested objects (User
Objects) mapping relationship.
3.2 Collection Mapping
Suppose there is oneUser
Class, which contains an order list:
public class User { private int id; private String name; private String email; private List<Order> orders; // getters and setters }
Configure collection mapping in MyBatis mapping file:
<mapper namespace=""> <resultMap type=""> <id property="id" column="id" /> <result property="name" column="name" /> <result property="email" column="email" /> <collection property="orders" ofType=""> <id property="id" column="order_id" /> <result property="orderDate" column="order_date" /> </collection> </resultMap> <select resultMap="UserResultMap"> SELECT , , , AS order_id, o.order_date FROM users u LEFT JOIN orders o ON = o.user_id WHERE = #{id} </select> </mapper>
Here,collection
Elements are used to define and set (orders
List) mapping relationship.
4. Dynamic result mapping
MyBatis supports dynamic result mapping, through<resultMap>
Elements can dynamically define the structure of the result map:
<resultMap type=""> <id property="id" column="id" /> <result property="name" column="name" /> <result property="email" column="email" /> </resultMap> <select resultMap="DynamicResultMap"> SELECT id, name, email FROM users WHERE id = #{id} </select>
Here, the query results will be mapped toHashMap
In the object, the key is the column name and the value is the corresponding column value.
5. Lazy Loading
MyBatis supports lazy loading and only queries are done when actually using nested objects or collections:
In MyBatis configuration file (Enable lazy loading in ):
<configuration> <settings> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings> </configuration>
After the configuration is completed, the corresponding query will be triggered only when accessing nested objects or collections to improve performance.
6. Summary
MyBatis' result mapping mechanism greatly facilitates the conversion between complex query results and Java objects. By rationally configuring the result map, complex structures such as nested objects and collections can be easily processed, improving the readability and maintainability of the code. This article introduces the configuration methods of basic and complex result mapping in MyBatis, hoping to help you better grasp the use of MyBatis.
To further learn about MyBatis result mapping, you can refer to the following resources:
- MyBatis official documentation
- MyBatis User Guide
This is the end of this article about the two methods of MyBatis result mapping. For more related contents of MyBatis result mapping, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!