一对多:
子查询 (效率低 发送sql语句多)
1. 在 Teacher 中添加 List<Student>
public class Teacher {
private int id;
private String name;
private List<Student> students= new ArrayList<>(); //一对多 一个老师对多个学生
2. 在 StudentMapper.xml 中添加通过 tid 查询
<select id="selByTid" parameterType="int" resultType="student">
select * from student where tid=#{0}
</select>
3. 在 TeacherMapper.xml 中添加查询全部
3.1
<collection/> 当属性是集合类型时使用的标签.
<resultMap type="teacher" id="mymap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="students" ofType="student" select="包名.StudentMapper.selByTid"
column="id">
</collection>
</resultMap>
<select id="selAll" resultMap="mymap">
select * from teacher
</select>
关联查询
在 teacherMapper.xml 中添加
mybatis 可以通过主键判断对象是否被加载过.
不需要担心创建重复 Teacher
<resultMap type="teacher" id="mymap1">
<id column="tid" property="id"/>
<result column="tname" property="name"/>
<collection property="students" ofType="student" >
<id column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="age" property="age"/>
</collection>
</resultMap>
<select id="selAll1" resultMap="mymap1">
select t.id tid,t.name tname,s.id sid,s.name sname,age,tid from teacher t LEFT JOIN student s on t.id=s.tid;
</select>