Mybatis-04(关联表查询)

前言

利用mybatis框架,使用简单的xml配置映射成数据库中的记录

多表联查
  • 数据库建表
//建立两张表,教师表,班级表
//先建立教师表,因为教师和班级有关联,教师id是班级表的外键
CREATE TABLE teacher{
        t_id INT PRIMARY KEY AUTO_INCREMENT,
        t_name VARCHAR(20)
};
CREATE TABLE class{
      c_id INT PRIMARY KEY AUTO_INCREMENT,
     c_name VARCHAR(20),
     teacher_id INT      
}
ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREING KEY(teacher_id)REFERENCES
目录结构

在这里插入图片描述

  • 建立实体类
public class Teacher {
    private int id;
    private String name;
    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

public class Classes {
    private int id;
    private String name;
    private Teacher teacher;
    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public Teacher getTeacher() {return teacher;}
    public void setTeacher(Teacher teacher) {this.teacher = teacher;}
}
  • 建立ClassMapper.xml文件
//方法一:
//使用嵌套结果封装联表查询的数据
<select id="getClass" parameterType="int" resultMap="getClassMap">
    SELECT * FROM class c, teacher t WHERE c.teacher_id=t.tc_id AND c.c_id=#{id]
</select>
<resultMap type="Classes" id="getClassMap">
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <!--association关联的意思,关联到teacher-->
        <association property="teacher" javaType="Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </association>
 </resultMap>
方法二:
//利用上个sql语句的结果作为下次查询的条件
<select id="getClass2" parameterType="int" resultMap="getClass2Map">
    SELECT * FROM class WHERE c_id=#{id}
</select>
<select id="getTeacher" parameterType="int" resultMap="Teacher">
    SELECT t_id id,t_name name From teacher WHERE t_id=#{id}
</select>

<resultMap type="Classes" id="getClass2Map">
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
      
        <association property="teacher" javaType="Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </association>
 </resultMap>
  • 在配置文件注册
<mapper resource="com/atguigu/day03_mybatis/Test5/ClassMapper.xml"/>
  • 测试
public class test5 {
    @Test
    public void testSelect(){
        SqlSessionFactory factory = MybatisUtils.getFactory();
        SqlSession session = factory.openSession();
        String statement = "com.atguigu.day03_mybatis.Test5.ClassMapper.getClass";
        Classes c = session.selectOne(statement,2);
        System.out.println(c);
        session.close();
    }
}

//方法二在测试类里面调用 String statement = "com.atguigu.day03_mybatis.Test5.ClassMapper.getClass2";

  • 结果
    在这里插入图片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章