场景
当我们需要查询一个班集里所有学生信息时,需要用到一对多的查询,此时使用Mybatis的collection属性处理。实例
ClassInfo.java
public class ClassInfo {
private String className;
private String classCode;
private String chargeMan;
private List<Student> students;
public void setClassName (String className) {
this.className = className;
}
public String getClassName () {
return this.className;
}
... ...
}
Student.java
public class Student {
private String name;
private int age;
private String sex;
private String classCode;
public void setName (String name) {
this.name = name;
}
public String getName () {
return this.name;
}
... ...
}
ClassInfoMapper.java
public interface ClassInfoMapper {
ClassInfo getClassAndStudentInfoByClassCode (String classCode);
}
ClassInfoMapper.xml
<select id="getClassAndStudentInfoByClassCode" resultMap="classAndStudentMap">
SELET class_name, c.class_code, name, class_charge, s.class_code, age, sex
FROM class AS c LEFT JOIN student AS s ON c.class_code = s.class_code
WHERE c.class_code = #{class_code}
</select>
<resultMap id="classAndStudentMap" type="com.cat.pojo.ClassInfo">
<result column="class_code" property="classCode" />
<result column="class_name" property="className" />
<result column="charge_man" property="chargeMan" />
<collection property="students" ofType="com.cat.pojo.Student">
<result column="name" property="name"/>
<result column="age" property="age" />
<result column="sex" property="sex" />
</collection>
</resultMap>
通过以上的配制便可实现样合查询的集合属性封装。