在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时,要确保映射的字段名与自定义对象的属性名一致,否则映射会失败。