What is the usage of the oftype tag in MyBatis?

The tag in MyBatis is used to specify the type of the returned result in the mapping file. Typically, MyBatis automatically maps the query results based on the column names and Java object property names. However, in some cases, manual mapping of types may be required, and this is when the tag can be used.

There are two different ways to use the tag:

  1. kind
<resultMap id="userResultMap" type="com.example.User">
  <id property="id" column="id"/>
  <result property="name" column="name"/>
  <result property="age" column="age" ofType="java.lang.Integer"/>
</resultMap>

In the example above, the ofType attribute in the tag specifies the type of the returned age field as java.lang.Integer.

<resultMap id="userResultMap" type="com.example.User">
  <id property="id" column="id"/>
  <result property="name" column="name"/>
  <result property="age" column="age">
    <ofType javaType="java.lang.Integer"/>
  </result>
</resultMap>

In the example above, the tag nests the tag and specifies the type of the returned age field as java.lang.Integer using the javaType attribute.

By using the tag, you can ensure that the query results are mapped to Java objects using the specified type, to avoid type conversion errors.

广告
Closing in 10 seconds
bannerAds