现在是在mybatis中实现
一.多个学生关联一个老师(多对一)
定义两个实体类:
方式一:
<!--方法一 多表查询-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<!--property 对应实体类属性,column对应数据库字段-->
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性需要单独处理-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
<!--select去查teacher表,将查出来的结果给Student中的teacher-->
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
方式二:
<!--方法二 按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid=t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
查询结果:
二 . 一个老师包含多个学生(一对多)
实体类:
方式一:
<select id="getTeacherById" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from teacher t,student s
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result column="id" property="id"/>
<result property="name" column="tname"/>
<!--复杂的属性,如 集合,就需要单独处理-->
<!--ofType表示集合的约束类型-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
方式二:
<select id="getTeacherById2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid};
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTId" column="id"/>
</resultMap>
<select id="getStudentByTId" resultType="Student">
select * from student where tid=#{tid}
</select>
小结
1.关联:association(多对一)
2.包含:collection(一对多)
3.javaType:用于指定实体类中属性的类型
4.ofType:用于指定映射到List或者集合中的实体类的类型,即泛型的约束类型