11.一对多处理查询—集合—使用list集合—collection映射
1.Student.java和Teacher.java
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
//老师这里是集合,所以在后面映射需要用collection
private List<Student> students;
}
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
2.StudentMapper.java和TeacherMapper.java
public interface StudentMapper {
}
import com.kuang.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TeacherMapper {
//获取所有老师,这里可以注解开发,也可以xml配置文件
public List<Teacher> getTeacher();
//获取给定老师id,获取老师下的所有学生信息以及老师信息,一对多
Teacher getTeachers(@Param("tid") int id);
//方式二,
Teacher getTeachers2(@Param("tid") int id);
}
3.MybatisUtils.java和mybatis-config.xml,db.properties同上
4.重点,一对多查询的实现
TeacherMapper.xml
<mapper namespace="com.kuang.dao.TeacherMapper">
<!--方式一,根据结果集查询,因为前面类中定义的是集合,所以,这里映射要用collection-->
<select id="getTeachers" resultMap="TeacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname from teacher t,student s
where t.id=s.tid and t.id=#{tid}
</select>
<!--复杂的属性,我们需要单独处理,
对象:association,
集合:collection
javaType是属性的类型,
集合中的泛型,我们用ofType来解决
-->
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname">