mybatis

如何在MyBatis中动态设置resultType

小樊
84
2024-09-05 03:56:01
栏目: 编程语言

在 MyBatis 中,你可以使用动态 SQL 功能来动态设置 resultType。这主要涉及到使用 和<otherwise> 标签来根据不同的条件选择不同的 resultType。

以下是一个示例,展示了如何在 MyBatis 的 XML 映射文件中动态设置 resultType:

  SELECT
    id,
    username,
    email,
    age
  FROM
    users
  WHERE
    1 = 1
    <if test="id != null">
      AND id = #{id}
    </if>
    <if test="username != null">
      AND username = #{username}
    </if>
</select><resultMap id="dynamicResultMap" type="map">
 <result property="id" column="id"/>
 <result property="username" column="username"/>
 <result property="email" column="email"/>
 <result property="age" column="age"/>
 <choose>
    <when test="age != null">
     <result property="age" column="age" javaType="java.lang.Integer"/>
    </when>
   <otherwise>
     <result property="age" column="age" javaType="java.lang.String"/>
    </otherwise>
  </choose>
</resultMap>

在这个示例中,我们根据 age 字段是否为空来动态设置 resultType。如果 age 不为空,则将其作为整数(java.lang.Integer)返回;否则,将其作为字符串(java.lang.String)返回。

请注意,这个示例仅用于演示目的。在实际应用中,你可能需要根据你的需求和数据结构进行调整。

0
看了该问题的人还看了