在MyBatis中,可以通過自定義ResultMap來映射查詢結果到自定義對象。以下是一個簡單的示例:
<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);
通過以上步驟,就可以將查詢結果映射到自定義對象CustomObject中了。需要注意的是,在定義ResultMap時,要確保映射的字段名與自定義對象的屬性名一致,否則映射會失敗。