9.1 多对一需求代码编写

9.1 多对一需求代码编写

需求:查询所有学生信息,以及对应的老师信息

方法一:按照查询嵌套处理(子查询)

  • sql语句:select s.id,s.name,t.id from student s where t.id=(select id from teacher )

第一步:编写mapper接口

 public interface StudentMapper {
 
     //需求:查询所有学生信息,以及对应的老师信息
     List<Student> findAllStudents()throws Exception;
 }
 public interface TeacherMapper {
 
     Teacher findTeacherById(Integer id)throws Exception;
 }

第二步:编写StudentMapper.xml配置文件(关键)

  • 关键一:我们需要先查出学生表的所有信息

  • 关键二:通过id查出教师表的相应信息,因为我们学生实体类是关联到教师类的

  • 关键三:通过ResultMap做映射处理 前两个字段就正常写,复杂属性通过官网我们知道要使用association标签,需要制定类型以及sql语句 也可以说是套娃学生sql套teacher的sql

 <?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE mapper
         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <!--namespace命名空间-->
 <mapper namespace="com.xuan.mapper.StudentMapper">
 
     <resultMap id="studentMap" type="Student">
         <id property="id" column="id"></id>
         <result property="name" column="name"></result>
         <!--复杂属性我们不用result-->
         <association property="teacher" column="tid" javaType="Teacher" select="findTeacherById" ></association>
     </resultMap>
 
     <select id="findAllStudents" resultMap="studentMap">
        select * from student
     </select>
 
     <select id="findTeacherById" parameterType="int" resultType="Teacher">
        select * from teacher where id =#{id}
     </select>
 </mapper>

第三步:编写测试

 @Test
 public void testFindAllStudents() throws Exception {
     SqlSession sqlSession = MyBatisUtil.getSqlSession();
     StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
 
     List<Student> students = mapper.findAllStudents();
     for (Student student : students) {
         System.out.println(student);
    }
 
     sqlSession.close();
 }

---------------------------------------测试成功-----------------------------------------

方法二: 按照结果嵌套处理(联表查询)

  • sql语句 select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id

  • 其他都与按照查询嵌套处理方式一致,这里就写关键处

  • 编写StudentMapper.xml配置文件

 <resultMap id="studentMap" type="Student">
     <result property="id" column="sid"></result>
     <result property="name" column="sname"></result>
     <association property="teacher" javaType="Teacher">
         <result property="name" column="tname"></result>
     </association>
 </resultMap>
 
 <select id="findAllStudents" resultMap="studentMap">
    select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
 </select>

 

 

posted @ 2020-07-16 21:31  xuan_study  阅读(181)  评论(0)    收藏  举报