The cause of

In actual business, we often encounter one-to-many data relationship. For example, there are multiple students in a class, and we need to include all these students when querying the class

The solution

Use The resultMap and Collection of Mybatis to realize the query of one-to-many relationship, the code is as follows

<resultMap id="ClassResult" type="cn.houtaroy.school.entities.ClassEntity">
    <id property="id" column="id"/>
    <result property="no" column="no"/>
    <result property="name" column="name"/>
    <collection property="students"
                ofType="cn.houtaroy.school.entities.StudentEntity"
                javaType="java.util.ArrayList"
                select="cn.houtaroy.school.repositories.StudentRepository.listByClassId"
                column="id">
    </collection>
</resultMap>
Copy the code

Where collection tag is the actual array of students, SELECT is the query statement, column primary key ID parameter, roughly query statement as follows:

select id, name, sex, age from t_student where class_id = #{id}
Copy the code

multi-parameter

The above method only passes in the class ID. What if I also need to pass in the class type? At this point we need to adjust the contents of column:

<collection property="students"
            ofType="cn.houtaroy.school.entities.StudentEntity"
            javaType="java.util.ArrayList"
            select="cn.houtaroy.school.repositories.StudentRepository.listByClassId"
            column="{id=id, classType=type}">
</collection>
Copy the code

That is {attribute name 1= column name 1, attribute name 2= column name 2… }

Then in the SQL statement change to:

select id, name, sex, age from t_student where class_id = #{id} and class_type = #{classType}
Copy the code