What is the difference between resulttype and resultmap in mybatis?
In MyBatis, both resultType and resultMap are used to specify the mapping method of query results, but there are some differences:
- resultType is used to specify the mapping type of the query result. It can be a Java primitive type, JavaBean, or collection type. When the query result has only one field, you can use resultType to specify the mapping type. For example:
- Retrieve the name of the user from the database where the user’s ID matches the input ID.
- When there are multiple fields in the query result, it is not possible to use resultType for mapping, you need to use resultMap.
- resultMap is used to define the mapping rules for query results. It allows custom mapping of fields from query results to Java object properties, and must be defined in the Mapper XML file. For example:
- The
named userResultMap is defined for mapping columns from the User table to properties in the com.example.User class. The - In the example above, the resultMap is defined with an ID of userResultMap, specifying the mapping rules for the query result fields user_id, user_name, and user_age to the properties id, name, and age of the User object. This mapping rule is referenced in the select statement using the resultMap property. When there are multiple fields in the query result and complex mapping relationships need to be handled, resultMap can be used.
In conclusion, resultType is suitable for simple query result mapping, while resultMap is suitable for complex query result mapping.