Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mybatis

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?

like image 689
guogangj Avatar asked Jun 04 '14 12:06

guogangj


People also ask

What is parameter type in MyBatis?

parameterType. The fully qualified class name or alias for the parameter that will be passed into this statement. This attribute is optional because MyBatis can calculate the TypeHandler to use out of the actual parameter passed to the statement. Default is unset .

What is the difference between Ibatis and MyBatis?

It is the same thing, a persistence framework! But until June 2010, iBatis was under Apache license and since then, the framework founders decided to move it to Google Code and they renamed it to MyBatis. The framework is still the same though, it just has a different name now.

What is resultMap in MyBatis?

resultMaps. It is the most important and powerful elements in MyBatis. The results of SQL SELECT statements are mapped to Java objects (beans/POJO). Once the result map is defined, we can refer these from several SELECT statements.

What is TypeHandler in MyBatis?

typeHandlers. Whenever MyBatis sets a parameter on a PreparedStatement or retrieves a value from a ResultSet, a TypeHandler is used to retrieve the value in a means appropriate to the Java type.


1 Answers

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.

like image 60
nivekastoreth Avatar answered Sep 28 '22 00:09

nivekastoreth