Git007

导航

【MyBatis学习】03、一对多查询

1.创建pojo (Teacher、Student)

@Data
public class Teacher {
    private int id;
    private String name;

    private List<Student> students;
}
@Data
public class Student {
    private int id;
    private String name;

}

2.创建对应的Mapper文件

public interface TeacherMapper {
    //根据id找到老师,并包括学生信息
    Teacher getTeacherById(@Param("tid") int id);
}
public interface StudentMapper {

}

3.编写对应的Mapper.xml文件

   利用结果嵌套查询

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcl.dao.TeacherMapper">
    <select id="getTeacherById" 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=1;
    </select>
    
    <resultMap id="TeacherStudent" type="teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
    </resultMap>
</mapper>

4.在mybatis-config.xml配置文件中注册Mapper

 <mappers>
        <mapper class="com.wcl.dao.StudentMapper"/>
        <mapper class="com.wcl.dao.TeacherMapper"></mapper>
    </mappers>

5.测试

public class MyTest {
    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacherById(1);
        System.out.println(teacher);
        sqlSession.close();

    }
}

总结:

  • 关联 association (多对1、对象)
  • 集合 collection(1对多、集合)
  • JavaType & ofType
  1. JavaType 用来指定实体类中的属性
  2. ofType 用来映射到List或集合中pojo类型,或者说泛型类型

面试高频:

  • Mysql引擎
  • Innodb底层原理
  • 索引
  • 索引优化

 

posted on 2022-02-22 20:01  cczzhh007  阅读(36)  评论(0)    收藏  举报