首页 > 其他分享 >mybatis关联映射(1对多、多对1)

mybatis关联映射(1对多、多对1)

时间:2022-12-28 21:45:30浏览次数:70  
标签:return 映射 students id long 关联 void mybatis public

 

准备测试数据

班级表

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for classes
-- ----------------------------
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
  `c_id` int(11) NOT NULL AUTO_INCREMENT,
  `c_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`c_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of classes
-- ----------------------------
INSERT INTO `classes` VALUES ('1', 'java');
INSERT INTO `classes` VALUES ('2', 'python');

  

学生表

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for students
-- ----------------------------
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
  `s_id` int(11) NOT NULL AUTO_INCREMENT,
  `s_name` varchar(255) DEFAULT NULL,
  `s_age` int(11) DEFAULT NULL,
  `class_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`s_id`),
  KEY `fk_class_id` (`class_id`),
  CONSTRAINT `fk_class_id` FOREIGN KEY (`class_id`) REFERENCES `classes` (`c_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of students
-- ----------------------------
INSERT INTO `students` VALUES ('1', 'jack', '18', '1');
INSERT INTO `students` VALUES ('2', 'tom', '19', '2');
INSERT INTO `students` VALUES ('3', 'laowang', '20', '1');
INSERT INTO `students` VALUES ('4', 'liming', '19', '2');
INSERT INTO `students` VALUES ('5', 'lucy', '19', '1');

 

模型

 

示例

配置及测试一对多:根据班级查学生

班级实体类:里面要加学生集合属性,private List<Students> students

package com.qzcsbj.bean;


import java.util.List;

public class Classes {

  private long cId;
  private String cName;
  // 学生集合
  private List<Students> students;

  public long getCId() {
    return cId;
  }

  public void setCId(long cId) {
    this.cId = cId;
  }

  public String getCName() {
    return cName;
  }

  public void setCName(String cName) {
    this.cName = cName;
  }

  public List<Students> getStudents() {
    return students;
  }

  public void setStudents(List<Students> students) {
    this.students = students;
  }

  @Override
  public String toString() {
    return "Classes{" +
            "cId=" + cId +
            ", cName='" + cName + '\'' +
            '}';
  }
}

 

学生实体类

package com.qzcsbj.bean;


public class Students {

  private long sId;
  private String sName;
  private long sAge;
  private long classId;


  public long getSId() {
    return sId;
  }

  public void setSId(long sId) {
    this.sId = sId;
  }


  public String getSName() {
    return sName;
  }

  public void setSName(String sName) {
    this.sName = sName;
  }


  public long getSAge() {
    return sAge;
  }

  public void setSAge(long sAge) {
    this.sAge = sAge;
  }


  public long getClassId() {
    return classId;
  }

  public void setClassId(long classId) {
    this.classId = classId;
  }

  @Override
  public String toString() {
    return "Students{" +
            "sId=" + sId +
            ", sName='" + sName + '\'' +
            ", sAge=" + sAge +
            ", classId=" + classId +
            '}';
  }
}

  

mapper接口

package com.qzcsbj.mapper;

import com.qzcsbj.bean.Classes;

import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public interface ClassesMapper {
    // 1对n:根据班级id查询班级信息,包含班级下的学生信息
    public Classes getClassesById(int cId);
}

  

映射文件:ClassesMapper.xml

    <!--班级下有学生集合-->
    <resultMap id="classesMap2" type="Classes">
        <id column="c_id" property="cId"/>
        <result column="c_name" property="cName"/>
        <!--集合-->
        <collection property="students" ofType="Students">
            <id column="s_id" property="sId"/>
            <result column="s_name" property="sName"/>
            <result column="s_age" property="sAge"/>
            <result column="class_id" property="classId"/>
        </collection>
    </resultMap>

    <!--根据班级id查询班级信息,包含班级下的学生信息-->
    <select id="getClassesById" resultMap="classesMap2">
        select * from classes c join students s on c.c_id = s.class_id
        where c.c_id=#{cId}
    </select>

  

测试类

    @Test
    public void testGetClassesById(){
        Classes c = classesMapper.getClassesById(1);
        System.out.println("班级信息:" + c);
        System.out.println("班级下的学生信息:");
        List<Students> students = c.getStudents();
        for (Students student : students) {
            System.out.println(student);
        }
    }

  

结果

 

 

配置及测试多对一:根据学生查班级

学生实体类:需要加班级对象属性

package com.qzcsbj.bean;


public class Students {

  private long sId;
  private String sName;
  private long sAge;
  private long classId;
  private Classes classes;


  public long getSId() {
    return sId;
  }

  public void setSId(long sId) {
    this.sId = sId;
  }


  public String getSName() {
    return sName;
  }

  public void setSName(String sName) {
    this.sName = sName;
  }


  public long getSAge() {
    return sAge;
  }

  public void setSAge(long sAge) {
    this.sAge = sAge;
  }


  public long getClassId() {
    return classId;
  }

  public void setClassId(long classId) {
    this.classId = classId;
  }

  public Classes getClasses() {
    return classes;
  }

  public void setClasses(Classes classes) {
    this.classes = classes;
  }

  @Override
  public String toString() {
    return "Students{" +
            "sId=" + sId +
            ", sName='" + sName + '\'' +
            ", sAge=" + sAge +
            ", classId=" + classId +
            '}';
  }
}

  

班级实体类

package com.qzcsbj.bean;


import java.util.List;

public class Classes {

  private long cId;
  private String cName;
  private List<Students> students;

  public long getCId() {
    return cId;
  }

  public void setCId(long cId) {
    this.cId = cId;
  }

  public String getCName() {
    return cName;
  }

  public void setCName(String cName) {
    this.cName = cName;
  }

  public List<Students> getStudents() {
    return students;
  }

  public void setStudents(List<Students> students) {
    this.students = students;
  }

  @Override
  public String toString() {
    return "Classes{" +
            "cId=" + cId +
            ", cName='" + cName + '\'' +
            '}';
  }
}

 

mapper接口

package com.qzcsbj.mapper;

import com.qzcsbj.bean.Students;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public interface StudentsMapper {
    // 根据学生id查学生信息,包含该学生的班级信息
    public Students getStudentsById(int sId);
}

  

映射文件:StudentsMapper.xml

<?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.qzcsbj.mapper.StudentsMapper">

    <select id="getStudentsById" resultMap="StudentMap">
        select * from students s join classes c on c.c_id=s.class_id
        where s.s_id=#{sId}
    </select>

    <resultMap id="StudentMap" type="Students">
        <id column="s_id" property="sId"/>
        <result column="s_name" property="sName"/>
        <result column="s_age" property="sAge"/>
        <result column="class_id" property="classId"/>
        <!--一个用association-->
        <association property="classes" javaType="Classes">
            <id column="c_id" property="cId"/>
            <result column="c_name" property="cName"/>
        </association>
    </resultMap>
</mapper>

  

测试类

    @Test
    public void testGetStudentsById(){
        Students stu = studentsMapper.getStudentsById(1);
        System.out.println("学生的信息是:" + stu);
        Classes c = stu.getClasses();
        System.out.println("该学生的班级信息是:" + c);
    }

  

结果

 

【bak】

 

原文会持续更新,原文地址:https://www.cnblogs.com/uncleyong/p/17009234.html

 

标签:return,映射,students,id,long,关联,void,mybatis,public
From: https://www.cnblogs.com/uncleyong/p/17009785.html

相关文章

  • 爱上 Mybatis源码 (2019-08-11)
     第一次学习源码,自己很难吃透源码,也做不到直接撸源码,一句一句的解析。先学习一下别人的文章,吃透源码的流程,日后有能力了再逐句撸。 源码的乐趣就在于首先能明白为什么我......
  • centos7修改静态ip,主机名,主机映射
    centos7配置一.修改主机名​​root用户操作​​vim/etc/hostnamehadoop201#添加要设置的主机名​​重启虚拟机生效​​二.添加ip和hostname对应关系即主机映射vim/e......
  • 评价类模型 - 灰色关联模型
    目的:考察某个指标与其它指标的关联程度大小解决:将某个指标设为参考数列,(当然所有指标都需要经过标准化去量纲,一般采用初值化(都除以第一个元素))利用公式求出每个人对应的每......
  • C++/Qt 系列推荐 - ORM(对象关系映射)
    教程目录以下是教程目录,从理论到实战,一步步深入ORM:​​快速认识ORM​​​​QxOrm介绍、下载、编译​​​​QxOrm快速上手​​​​在Ubuntu上安装MySQL​​​​QMYSQL......
  • 【博学谷学习记录】超强总结,用心分享。mybatis框架的一些重要知识点。
    一、MyBatis框架1.1谈一谈对mybatis框架的理解。mybatis是一款优秀的持久层框架,一个半ORM(对象关系映射)框架,它支持定制化SQL、存储过程以及高级映射......
  • MySQL多表关联查询+子查询_R
    MySQL多表关联查询+子查询--**************关联查询(多表查询)****************--多表查询规则:1)确定查询哪些表。2)确定哪些字段。3)表与表之间连接关系(规律:连接条件数......
  • mybatis批量update(mysql)
    批量插入:<insertid="batchInsert">insertintotestTable(id,content)values<foreachcollection="list"item="item"index="index"separator=",">......
  • Mybatis 的<trim>标签用法 prefix prefixOverrides suffix suffixOverrides
    <trimprefix=""suffix=""suffixOverrides=""prefixOverrides=""></trim>prefix:在trim标签内sql语句加上前缀。prefixOverrides:指定去除多余的前缀内容如:prefixOve......
  • 【SSM框架】MyBatis核心配置文件详解
    1.MyBatis核心配置文件之environments<!--environments:配置多个连接数据库的环境属性:default:设置默认使用的环境的id--><environmentsdefault="development"><!......
  • GPIO复用与端口重映射
    GPIO复用GPIO复用为内置外设的功能,如果这个GPIO要作为内置外设使用,那么就要使用GPIO复用的功能了RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//①IO时钟使能......