SoFunction
Updated on 2025-03-08

Use of MyBatis result map (ResultMap)

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 useResultMapto 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_nameand Java objectsusernameMis match. In this case, it can be passedResultMapTo 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 objectsidAttributes.
  • <result>Tags are used to define mapping relationships for ordinary fields.

DefinitionResultMapAfter 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 toUserObject, even if the database field does not match the Java property name.

2. Field Mapping Type

ResultMapSupports 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 tableidField mapped to Java objectsidAttributes.

2.2 General field mapping

<result>Tags are used to map non-primary key fields. For example,user_nameMap tousername

<result column="user_name" property="username" />

2.3 Nested Object Mapping

ResultMapSupport mapping certain fields in the query results into nested objects of Java objects. For example, ifUserThe class contains oneAddressObjects 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
}

AssumptionusersThere are the following fields in the table:

  • street: Street name
  • city: City name

Can be passedResultMapMap these fields toUser In the object AddressAttributes:

<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 willAddressThe fields of the class and the query resultsstreetandcityMap.

2.4 Collection Mapping

For one-to-many relationships, MyBatis provides<collection>Tags to handle collection mapping. Assume oneUserHave 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
}

AssumptionordersTable andusersTable passeduser_idAssociated, 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.ordersEach in the listOrderAll objects are from the query resultorder_idandorder_numberFill 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,OrderThe class contains oneUserObject:

public class Order {
    private int id;
    private String orderNumber;
    private User user;
    // getters and setters
}

You can pass the followingResultMapWillOrderandUserThe 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_iduser_nameandemailField map toOrder In the object UserAttributes.

3.2 One-to-many mapping

One-to-many relationships usually pass<collection>Tags to handle. AssumptionUserThe 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 ordersIn 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,OrderIncluded in the classUserObjects, 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 selectThe 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 isINTtype(0Represents a male,`

1Represents a female), and the properties in the Java class areStringtype(“Male"and"Female”), can be customizedTypeHandler` implements type conversion:

public class GenderTypeHandler extends BaseTypeHandler&lt;String&gt; {
    @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'ResultMapIt 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!