In MyBatis,ResultMapIt is the core mechanism for mapping database query results to Java objects. It allows developers to flexibly define the mapping relationship between database table fields and Java object properties, especially when the field and attribute names are inconsistent, or when dealing with complex objects (such as nested objects, collections), ResultMap provides great convenience.
1. Basic concepts
By default, MyBatis can automatically map if the database field name and the attribute name of a Java object are exactly the same. However, when the field name and attribute name are inconsistent, or when complex object structures are involved, you need to useResultMap
to perform accurate mapping.
1.1 Basic Example
Suppose there is a simple database tableusers
, the structure is as follows:
CREATE TABLE users ( id INT PRIMARY KEY, user_name VARCHAR(50), email VARCHAR(100) );
And a corresponding Java class:
public class User { private int id; private String username; private String email; // getters and setters }
In SQL query, the table's fieldsuser_name
and Java objectsusername
Mis match. In this case, it can be passedResultMap
To manually specify the mapping relationship:
<resultMap type=""> <id column="id" property="id" /> <result column="user_name" property="username" /> <result column="email" property="email" /> </resultMap>
Here:
-
<id>
Tags are used to specify the primary key field mapped to Java objectsid
Attributes. -
<result>
Tags are used to define mapping relationships for ordinary fields.
DefinitionResultMap
After that, you can reference it in the SQL query:
<select resultMap="userResultMap"> SELECT id, user_name, email FROM users WHERE id = #{id} </select>
In this way, MyBatis will automatically map the database query results toUser
Object, even if the database field does not match the Java property name.
2. Field Mapping Type
ResultMap
Supports multiple field mapping types to meet the mapping requirements of different database fields and Java attributes.
2.1 ID Mapping
<id>
Tags are used to specify the primary key field of the database table and map to the primary key attributes in Java objects. For example:
<id column="id" property="id" />
This will be in the database tableid
Field mapped to Java objectsid
Attributes.
2.2 General field mapping
<result>
Tags are used to map non-primary key fields. For example,user_name
Map tousername
:
<result column="user_name" property="username" />
2.3 Nested Object Mapping
ResultMap
Support mapping certain fields in the query results into nested objects of Java objects. For example, ifUser
The class contains oneAddress
Objects can be mapped like this:
public class User { private int id; private String username; private String email; private Address address; // getters and setters } public class Address { private String street; private String city; // getters and setters }
Assumptionusers
There are the following fields in the table:
-
street
: Street name -
city
: City name
Can be passedResultMap
Map these fields toUser
In the object Address
Attributes:
<resultMap type=""> <id column="id" property="id" /> <result column="user_name" property="username" /> <result column="email" property="email" /> <association property="address" javaType=""> <result column="street" property="street" /> <result column="city" property="city" /> </association> </resultMap>
Used here<association>
The tag willAddress
The fields of the class and the query resultsstreet
andcity
Map.
2.4 Collection Mapping
For one-to-many relationships, MyBatis provides<collection>
Tags to handle collection mapping. Assume oneUser
Have multipleOrder
, can be used<collection>
Mapping:
public class User { private int id; private String username; private List<Order> orders; // getters and setters } public class Order { private int id; private String orderNumber; // getters and setters }
Assumptionorders
Table andusers
Table passeduser_id
Associated, you can use the followingResultMap
:
<resultMap type=""> <id column="id" property="id" /> <result column="user_name" property="username" /> <collection property="orders" ofType=""> <id column="order_id" property="id" /> <result column="order_number" property="orderNumber" /> </collection> </resultMap>
Here<collection>
Tags are used to handle one-to-many relationships.orders
Each in the listOrder
All objects are from the query resultorder_id
andorder_number
Fill it.
3. Complex mapping: many to one and one to many
3.1 Many-to-one mapping
Many-to-one relationships usually pass<association>
Tags to handle. For example,Order
The class contains oneUser
Object:
public class Order { private int id; private String orderNumber; private User user; // getters and setters }
You can pass the followingResultMap
WillOrder
andUser
The association mapping:
<resultMap type=""> <id column="order_id" property="id" /> <result column="order_number" property="orderNumber" /> <association property="user" javaType=""> <id column="user_id" property="id" /> <result column="user_name" property="username" /> <result column="email" property="email" /> </association> </resultMap>
Here,<association>
Used to convert the query resultsuser_id
、user_name
andemail
Field map toOrder
In the object User
Attributes.
3.2 One-to-many mapping
One-to-many relationships usually pass<collection>
Tags to handle. AssumptionUser
The class contains multipleOrder
, Each user may have multiple orders, which can be configured like this:
<resultMap type=""> <id column="id" property="id" /> <result column="user_name" property="username" /> <collection property="orders" ofType=""> <id column="order_id" property="id" /> <result column="order_number" property="orderNumber" /> </collection> </resultMap>
When executing a query, MyBatis will automatically map the order list of each user toUser
In the object orders
In the collection.
4. Nested Query
Sometimes, it may not be appropriate to directly use nested result mapping due to performance issues or the data structure is too complex. MyBatis provides nested query functions, allowing the data of associated objects to be retrieved through subqueries when processing complex objects.
Nested query example
Suppose we have the following structure,Order
Included in the classUser
Objects, nested queries can be used:
<resultMap type=""> <id column="order_id" property="id" /> <result column="order_number" property="orderNumber" /> <association property="user" javaType="" select="findUserById" column="user_id" /> </resultMap> <select resultType=""> SELECT id, user_name, email FROM users WHERE id = #{id} </select>
In this example,<association>
In the tag select
The attribute is used to specify a separate query to obtain the associated object (User
), instead of getting it directly from the main query.
5. Custom type conversion
In some cases, the field type in the database may not be consistent with the Java object property type. MyBatis provides a type processor (TypeHandler
), used to convert between custom database types and Java types.
Custom TypeHandler Example
Assume that the gender field in the database isINT
type(0
Represents a male,`
1Represents a female), and the properties in the Java class are
Stringtype(
“Male"and
"Female”), can be customized
TypeHandler` implements type conversion:
public class GenderTypeHandler extends BaseTypeHandler<String> { @Override public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { (i, "Male".equals(parameter) ? 0 : 1); } @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLException { int gender = (columnName); return gender == 0 ? "Male" : "Female"; } //Other overloading methods are omitted}
Register customization in MyBatis configurationTypeHandler
:
<typeHandlers> <typeHandler javaType="" jdbcType="INTEGER" handler=""/> </typeHandlers>
This way, when processing gender fields, MyBatis automatically uses custom type conversion logic.
in conclusion
MyBatis'ResultMap
It is a powerful result mapping mechanism that allows developers to flexibly map database query results with Java objects. By usingResultMap
, can handle complex mapping scenarios such as inconsistent field names, nested objects, one-to-many, and many-to-one. Combining custom type conversion and nested queries, MyBatis provides a highly flexible persistence solution that can meet complex data mapping needs.
This is the end of this article about the use of MyBatis result mapping (ResultMap). 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!