How to make the myBatis select result(list) be set to object's property?

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like