MyBatis-07-笔记

Posted 寻7

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis-07-笔记相关的知识,希望对你有一定的参考价值。

MyBatis多表操作

1 多表模型介绍

  • 我们之前学习的都是基于单表操作的,而实际开发中,随着业务难度的加深,肯定需要多表操作的。
  • 多表模型分类 一对一:在任意一方建立外键,关联对方的主键。
  • 一对多:在多的一方建立外键,关联一的一方的主键。
  • 多对多:借助中间表,中间表至少两个字段,分别关联两张表的主键。

2 多表模型一对一操作

  1. 一对一模型: 人和身份证,一个人只有一个身份证

  2. 代码实现

    • 步骤一: sql语句准备

      CREATE TABLE person(
       	id INT PRIMARY KEY AUTO_INCREMENT,
       	NAME VARCHAR(20),
       	age INT
       );
       INSERT INTO person VALUES (NULL,'张三',23);
       INSERT INTO person VALUES (NULL,'李四',24);
       INSERT INTO person VALUES (NULL,'王五',25);
       
       CREATE TABLE card(
       	id INT PRIMARY KEY AUTO_INCREMENT,
       	number VARCHAR(30),
       	pid INT,
       	CONSTRAINT cp_fk FOREIGN KEY (pid) REFERENCES person(id)
       );
       INSERT INTO card VALUES (NULL,'12345',1);
       INSERT INTO card VALUES (NULL,'23456',2);
       INSERT INTO card VALUES (NULL,'34567',3);
      
    • 步骤二: 创建实体类

      package com.itheima.bean;
      
      public class Person {
          private Integer id;     //主键id
          private String name;    //人的姓名
          private Integer age;    //人的年龄
      
          public Person() {
          }
      
          public Person(Integer id, String name, Integer age) {
              this.id = id;
              this.name = name;
              this.age = age;
          }
      
          public Integer getId() {
              return id;
          }
      
          public void setId(Integer id) {
              this.id = id;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public Integer getAge() {
              return age;
          }
      
          public void setAge(Integer age) {
              this.age = age;
          }
      
          @Override
          public String toString() {
              return "Person{" +
                      "id=" + id +
                      ", name='" + name + '\\'' +
                      ", age=" + age +
                      '}';
          }
      }
      
      package com.itheima.bean;
      
      public class Card {
          private Integer id;     //主键id
          private String number;  //身份证号
      
          private Person p;       //所属人的对象
      
          public Card() {
          }
      
          public Card(Integer id, String number, Person p) {
              this.id = id;
              this.number = number;
              this.p = p;
          }
      
          public Integer getId() {
              return id;
          }
      
          public void setId(Integer id) {
              this.id = id;
          }
      
          public String getNumber() {
              return number;
          }
      
          public void setNumber(String number) {
              this.number = number;
          }
      
          public Person getP() {
              return p;
          }
      
          public void setP(Person p) {
              this.p = p;
          }
      
          @Override
          public String toString() {
              return "Card{" +
                      "id=" + id +
                      ", number='" + number + '\\'' +
                      ", p=" + p +
                      '}';
          }
      }
      
    • 步骤三: dao层的mapper接口定义

      package com.itheima.table01;
      
      import com.itheima.bean.Card;
      
      import java.util.List;
      
      public interface OneToOneMapper {
          //查询全部
          public abstract List<Card> selectAll();
      }
      
    • 步骤四: 映射配置文件

      <?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">
      
      <mapper namespace="com.itheima.table01.OneToOneMapper">
          <!--配置字段和实体对象属性的映射关系-->
          <!--仔细观察column对应的值都是SQL语句中的字段本身或者别名-->
          <resultMap id="oneToOne" type="card">
              <id column="cid" property="id" />
              <result column="number" property="number" />
              <!--
                  association:配置被包含对象的映射关系
                  property:被包含对象的变量名
                  javaType:被包含对象的数据类型
              -->
              <!--仔细观察column对应的值都是SQL语句中的字段本身或者别名-->
              <!--下面的property="p"中的p对应的是Card类中引用person对象的变量名-->
              <association property="p" javaType="person">
                  <id column="pid" property="id" />
                  <result column="name" property="name" />
                  <result column="age" property="age" />
              </association>
          </resultMap>
      
          <select id="selectAll" resultMap="oneToOne">
              SELECT c.id cid,number,pid,NAME,age FROM card c,person p WHERE c.pid=p.id
          </select>
      </mapper>
      
    • 步骤五: 测试类(目前相当于service层实现类)

       @Test
          public void selectAll() throws Exception{
              //1.加载核心配置文件
              InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
      
              //2.获取SqlSession工厂对象
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
      
              //3.通过工厂对象获取SqlSession对象
              SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
              //4.获取OneToOneMapper接口的实现类对象
              OneToOneMapper mapper = sqlSession.getMapper(OneToOneMapper.class);
      
              //5.调用实现类的方法,接收结果
              List<Card> list = mapper.selectAll();
      
              //6.处理结果
              for (Card c : list) {
                  System.out.println(c);
              }
      
              //7.释放资源
              sqlSession.close();
              is.close();
          }
      
  3. 一对一配置总结:

    <resultMap>:配置字段和对象属性的映射关系标签。
        id 属性:唯一标识
        type 属性:实体对象类型
    <id>:配置主键映射关系标签。
    <result>:配置非主键映射关系标签。
        column 属性:表中字段名称
        property 属性: 实体对象变量名称
    <association>:配置被包含对象的映射关系标签。
        property 属性:被包含对象的变量名
        javaType 属性:被包含对象的数据类型
    

3 多表模型一对多操作

  1. 一对多模型: 一对多模型:班级和学生,一个班级可以有多个学生。

  2. 代码实现

    • 步骤一: sql语句准备

      CREATE TABLE classes(
      	id INT PRIMARY KEY AUTO_INCREMENT,
      	NAME VARCHAR(20)
      );
      INSERT INTO classes VALUES (NULL,'一班');
      INSERT INTO classes VALUES (NULL,'二班');
      
      
      CREATE TABLE student(
      	id INT PRIMARY KEY AUTO_INCREMENT,
      	NAME VARCHAR(30),
      	age INT,
      	cid INT,
      	CONSTRAINT cs_fk FOREIGN KEY (cid) REFERENCES classes(id)
      );
      INSERT INTO student VALUES (NULL,'张三',23,1);
      INSERT INTO student VALUES (NULL,'李四',24,1);
      INSERT INTO student VALUES (NULL,'王五',25,2);
      INSERT INTO student VALUES (NULL,'赵六',26,2);
      
    • 步骤二: 创建实体类

      package com.itheima.bean;
      import java.util.List;
      
      public class Student {
          private Integer id;     //主键id
          private String name;    //学生姓名
          private Integer age;    //学生年龄
      
          public Student() {
          }
      
          public Student(Integer id, String name, Integer age) {
              this.id = id;
              this.name = name;
              this.age = age;
              this.courses = courses;
          }
      
          public Integer getId() {
              return id;
          }
      
          public void setId(Integer id) {
              this.id = id;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public Integer getAge() {
              return age;
          }
      
          public void setAge(Integer age) {
              this.age = age;
          }
      
          @Override
          public String toString() {
              return "Student{" +
                      "id=" + id +
                      ", name='" + name + '\\'' +
                      ", age=" + age +
                      '}';
          }
      }
      
      package com.itheima.bean;
      import java.util.List;
      
      public class Classes {
          private Integer id;     //主键id
          private String name;    //班级名称
      
          private List<Student> students; //班级中所有学生对象
      
          public Classes() {
          }
      
          public Classes(Integer id, String name, List<Student> students) {
              this.id = id;
              this.name = name;
              this.students = students;
          }
      
          public Integer getId() {
              return id;
          }
      
          public void setId(Integer id) {
              this.id = id;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public List<Student> getStudents() {
              return students;
          }
      
          public void setStudents(List<Student> students) {
              this.students = students;
          }
      
          @Override
          public String toString() {
              return "Classes{" +
                      "id=" + id +
                      ", name='" + name + '\\'' +
                      ", students=" + students +
                      '}';
          }
      }
      
    • 步骤三: dao层的mapper接口定义

      package com.itheima.table02;
      
      import com.itheima.bean.Classes;
      
      import java.util.List;
      
      public interface OneToManyMapper {
          //查询全部
          public abstract List<Classes> selectAll();
      }
      
    • 步骤四: 映射配置文件

      <?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">
      
      <mapper namespace="com.itheima.table02.OneToManyMapper">
          <resultMap id="oneToMany" type="classes">
              <id column="cid" property="id"/>
              <result column="cname" property="name"/>
      
              <!--
                  collection:配置被包含的集合对象映射关系
                  property:被包含对象的变量名
                  ofType:被包含对象的实际数据类型
              -->
               <!--仔细观察column对应的值都是SQL语句中的字段本身或者别名-->
              <!--下面的property="students"中的students对应的是Classes类中引用List<Student>对象的变量名-->
              <collection property="students" ofType="student">
                  <id column="sid" property="id"/>
                  <result column="sname" property="name"/>
                  <result column="sage" property="age"/>
              </collection>
          </resultMap>
          <select id="selectAll" resultMap="oneToMany">
              SELECT c.id cid,c.name cname,s.id sid,s.name sname,s.age sage FROM classes c,student s WHERE c.id=s.cid
          </select>
      </mapper>
      
    • 步骤五: 测试类(目前相当于service层实现类)

          @Test
          public void selectAll() throws Exception{
              //1.加载核心配置文件
              InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
      
              //2.获取SqlSession工厂对象
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
      
              //3.通过工厂对象获取SqlSession对象
              SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
              //4.获取OneToManyMapper接口的实现类对象
              OneToManyMapper mapper = sqlSession.getMapper(OneToManyMapper.class);
      
              //5.调用实现类的方法,接收结果
              List<Classes> classes = mapper.selectAll();
      
              //6.处理结果
              for (Classes cls : classes) {
                  System.out.println(cls.学习笔记:python3,代码片段(2017)

      [原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段

      sh bash片段 - 这些片段大多只是我自己的笔记;我找到了一些,有些我已经找到了

      需要一种有效的方法来避免使用 Laravel 5 重复代码片段

      Oracle-常用数据库对象笔记(片段)

      如何使用导航组件处理片段内的向上按钮