MyBatis ResultMap Value Conversion Guide
In MyBatis, resultMap can be used for result mapping and value conversion. MyBatis provides several ways to perform value conversion.
- By using the “typeHandler” attribute of resultMap, you can specify a typeHandler for each property in order to perform value conversion. TypeHandler is a Java class that implements the org.apache.ibatis.type.TypeHandler interface, and is used to convert values from the database into Java objects or vice versa. By using the typeHandler attribute in resultMap, you can specify a specific typeHandler for each property.
Original: 我们今天晚上九点开会。
Paraphrased: We have a meeting at 9 PM tonight.
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
<result property="username" column="username" />
<result property="password" column="password" />
<result property="email" column="email" typeHandler="com.example.EmailTypeHandler" />
</resultMap>
- By using the typeHandlers attribute in resultMap, you can specify a typeHandler for the entire resultMap. This way, when mapping results, MyBatis will use the specified typeHandler to convert all property values.
Example:
“The meeting was postponed until next week due to unforeseen circumstances.”
“The meeting had to be rescheduled for next week because of unexpected events.”
<resultMap id="userResultMap" type="User" typeHandlers="com.example.UserTypeHandler">
<id property="id" column="user_id" />
<result property="username" column="username" />
<result property="password" column="password" />
<result property="email" column="email" />
</resultMap>
- By using the @TypeDiscriminator annotation, you can specify a typeHandler that will choose different mapping rules based on the values in the database.
Can you please open the door for me?
-> Could you do me a favor and open the door?
@Results(id = "userResultMap", value = {
@Result(property = "id", column = "user_id", id = true),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password"),
@Result(property = "email", column = "email", typeHandler = EmailTypeHandler.class, javaType = Email.class,
options = { @Options(javaType = String.class, name = "value", typeHandler = EmailTypeHandler.class) })
})
@Select("SELECT * FROM users")
User getUser();
These are a few common methods for value conversion in MyBatis, and you can choose the appropriate method for value conversion based on your specific needs.