9.一对多

一对多处理

1)实体类编写

@Data
public class Student {
   private int id;
   private String name;
   private int tid;
}


@Data
public class Teacher {
   private int id;
   private String name;
   //一个老师多个学生
   private List<Student> students;
}

2)按结果嵌套处理

1.TeacherMapper接口编写方法

public Teacher getTeacher(int id);

2.编写接口对应的Mapper配置文件

<mapper namespace="com.xiaoguan.mapper.TeacherMapper">
    <!--
	思路:
		1.从学生表和老师表中查出学生id,学生姓名,老师姓名
		2.对查询出来的操作做结果集映射
			集合的话,使用collection
			javaType和ofType都是用来指定对象类型的
			javaType是用来指定pojo中属性的类型
			ofType指定的是映射到list集合属性中pojo的类型
-->
    <select id="getTeacher" resultMap="TeacherStudent">
    	select s.id sid, s.name sname, t.name tname, t.id tid
        from student s,teacher t
        where s.tid = t.id and t.id=#{id}
    </select>
    
    <resultMap id="TeacherStudent" type="Teacher">
    	<result property="name" column="tname"/>
        <collection property="students" ofType="Student">
        	<result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
</mapper>

3.将Mapper文件注册到mybatis-config文件中

<mappers>
	<mapper resource="mapper/TeacherMapper.xml"/>
</mappers>

4.测试

@Test
public void testGetTeacher(){
   SqlSession session = MybatisUtils.getSession();
   TeacherMapper mapper = session.getMapper(TeacherMapper.class);
   Teacher teacher = mapper.getTeacher(1);
   System.out.println(teacher.getName());
   System.out.println(teacher.getStudents());
}

3)按查询嵌套处理

1.TeacherMapper接口编写方法

public Teacher getTeacher2(int id);

2.编写接口对应的Mapper配置文件

<select id="getTeacher2" resultMap="TeacherStudent2">
	select *from teacher where id=#{id}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
	<!--column是一对多的外键,写的是一的主键的列名-->
    <collection property="students" javaType="ArrayList" ofType="Student"
                column="id" select="getStudentTeacherId"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
	select *from student where tid=#{id}
</select>

3.将Mapper文件注册到mybatis-config文件中

4.测试

@Test
public void testGetTeacher2(){
   SqlSession session = MybatisUtils.getSession();
   TeacherMapper mapper = session.getMapper(TeacherMapper.class);
   Teacher teacher = mapper.getTeacher2(1);
   System.out.println(teacher.getName());
   System.out.println(teacher.getStudents());
}

4)小结

1.关联-association

2.集合-collection

3.association是用于一对一和多对一,而collection是用于一对多的关系

4.javaType和ofType都是用来指定对象类型的

  • JavaTye是用来指定pojo中属性的类型
  • ofType指定的是映射到list集合属性中pojo的类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值