What is the difference between resultType and resultMap in MyBatis?
Both resultType and resultMap in MyBatis are used to map query results to Java objects, but they have some differences.
- The resultType is used to specify the type of a single result object, typically used when the query result only has one column, allowing the direct specification of a Java object type as the result.
<select id="selectUser" resultType="com.example.User">
SELECT id, name FROM user
</select>
- resultMap is used to specify complex mapping relationships, it allows specifying the mapping relationship between multiple fields and Java objects, and can achieve complex mapping relationships such as one-to-one and one-to-many.
<resultMap id="userResultMap" type="com.example.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
<select id="selectUser" resultMap="userResultMap">
SELECT id, name FROM user
</select>
In general, resultType is suitable for simple single result mappings, while resultMap is suitable for more complex mappings of multiple fields to Java objects.