Generally, myBatis's select method returns single object or generic List types. for example, I want to fetch all students of a class:
<select parameterType="int" resultMap="resultMapStudent"> SELECT * FROM students WHERE class_id=#{id}
</select>I can easily get a result like this: List<Student>.
Now, if I want to get the result like this rather than List<Student>:
class MyClass
{ List<Student> getStudents{return this.students;} void setStudents(List<Student> students){this.students = students} private List<Student> students;
}how can I do?
1 Answer
This is what the <collection/> element is for. It's important that you properly mark both the container and the values with their <id/> so that MyBatis knows how to deal with collapsing multiple rows into one object.
<resultMap type="some.package.MyClass" autoMapping="true"> <id property="classId" column="class_id" javaType="integer"/> <collection property="students" ofType="some.package.Student" autoMapping="true"> <id property="studentId" column="student_id" javaType="integer"/> </collection>
</resultMap>
<select parameterType="int" resultMap="resultMapClass"> SELECT * FROM students WHERE class_id = #{id}
</select>See for more details.
3