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

guogangj picture guogangj · Jun 4, 2014 · Viewed 36.6k times · Source

Generally, myBatis's select method returns single object or generic List types. for example, I want to fetch all students of a class:

<select id="fetchStudentsOfClass" 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?

Answer

nivekastoreth picture nivekastoreth · Jun 4, 2014

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 id="resultMapClass" 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 id="fetchStudentsOfClass" parameterType="int" resultMap="resultMapClass">
    SELECT *
    FROM students
    WHERE class_id = #{id}
</select>

See http://mybatis.github.io/mybatis-3/sqlmap-xml.html#Result_Maps for more details.