How to make an object property set for myBatis select (list) parameter?

Typically, the myBatis select method returns individual object types or generic types. For example, I want to get all the students in the class:

<select id="fetchStudentsOfClass" parameterType="int" resultMap="resultMapStudent"> SELECT * FROM students WHERE class_id=#{id} </select> 

I can easily get this result: List<Student> .

Now, if I want to get such a result, not a 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 this?

+6
source share
1 answer

This is what the <collection /> element is for. It is important that you correctly mark both the container and the values ​​with their <id /> so that MyBatis knows how to deal with folding multiple lines 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.imtqy.com/mybatis-3/sqlmap-xml.html#Result_Maps for details.

+7
source

Source: https://habr.com/ru/post/970308/


All Articles