在MyBatis中,可以通过自定义ResultMap来映射查询结果到自定义对象。以下是一个简单的示例:
首先,在映射文件中定义ResultMap,例如:<resultMap id="CustomObjectResultMap" type="com.example.CustomObject"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/></resultMap>然后,在查询语句中引用该ResultMap,例如:<select id="selectCustomObject" resultMap="CustomObjectResultMap"> SELECT id, name, age FROM custom_objects WHERE id = #{id}</select>最后,在Java代码中定义CustomObject类,并将查询结果映射到该类的实例中,例如:public class CustomObject { private Long id; private String name; private Integer age; // getters and setters}CustomObject customObject = sqlSession.selectOne("selectCustomObject", 1);通过以上步骤,就可以将查询结果映射到自定义对象CustomObject中了。需要注意的是,在定义ResultMap时,要确保映射的字段名与自定义对象的属性名一致,否则映射会失败。


