在MyBatis中,可以通過自定義ResultMap來映射查詢結(jié)果到自定義對(duì)象。以下是一個(gè)簡(jiǎn)單的示例:
<resultMap id="CustomObjectResultMap" type="com.example.CustomObject">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<select id="selectCustomObject" resultMap="CustomObjectResultMap">
SELECT id, name, age FROM custom_objects WHERE id = #{id}
</select>
public class CustomObject {
private Long id;
private String name;
private Integer age;
// getters and setters
}
CustomObject customObject = sqlSession.selectOne("selectCustomObject", 1);
通過以上步驟,就可以將查詢結(jié)果映射到自定義對(duì)象CustomObject中了。需要注意的是,在定義ResultMap時(shí),要確保映射的字段名與自定義對(duì)象的屬性名一致,否則映射會(huì)失敗。