Mybatis中collection的查询传参

1,057 阅读1分钟

起因

在实际业务中, 我们经常会遇到一对多的数据关系, 例如一个班级下有多名学生, 我们需要在查询班级的同时把这些学生也全部包含在内

解决方案

使用Mybatis的resultMap和collection, 实现一对多关系的查询, 代码如下

<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>

其中collection标签则为实际的学生数组, select为查询语句, column为主键id参数, 大概查询语句如下:

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

多参数

上面的方式只传入了班级id一个参数, 如果我还需要传入班级类型呢?此时我们需要调整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>

即{属性名称1=列名1, 属性名称2=列名2...}

然后在sql语句修改为:

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