0
点赞
收藏
分享

微信扫一扫

Mybatis多表操作

秦瑟读书 2022-01-27 阅读 70

文章目录


前言

mybatis的多表操作是最接近实际业务需求的操作,因此开一篇文章记录一下


一、一对一操作

使用mysql数据库

数据库环境

CREATE DATABASE db2;

USE db2;

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);

在这里插入图片描述

Mapper.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.ych.table01.OneToOneMapper">
<!--    配置字段和实体对象属性的映射关系-->
    <resultMap id="oneToOne" type="card">
        <id column="cid" property="id"/> <!--id专门为主键设置,其他都用result-->
        <result column="number" property="number"/>
<!--        association:用于配置被包含对象的映射关系
            property:被包含对象的变量名
            javaType:被包含对象的数据类型-->
        <association property="p" javaType="com.ych.bean.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>

重点是几个标签的使用——
在这里插入图片描述
在card类中包含了person类对象,因此需要association来再度封装person类对象。另外,由于mybatis框架会自动为我们创建实现类,因此我们只需要写好Mapper的接口

功能实现

public interface OneToOneMapper {
    /**
     * 查询全部的接口
     * @return
     */
    public abstract List<Card> selectAll();
}

接口的实现我们使用测试类+junit来完成

public class Test01 {
    
    @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);
        }

    }
}

遇到的问题

  • 解决org.apache.ibatis.executor.ExecutorException: No constructor found in xxxBean问题:需要写一个无参的构造方法,具体原因见连接https://blog.csdn.net/qq_35975416/article/details/80488267
  • 运行mybatis项目时找不到Mapper.xml配置文件:黑马的教学项目没有使用maven,我为了图省事用了maven,而在IDEA的maven项目中,默认源代码目录下(src/main/java目录)的xml等资源文件并不会在编译的时候一块打包进【target】目录下classes文件夹,我们运行时,是在target目录下去找Mapper.xml映射文件的,自然就会找不到了

二、一对多操作

数据库环境

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);

在这里插入图片描述

Mapper.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">
<!--namespace用于指定mapper接口的全路径-->
<mapper namespace="com.ych.table02.OneToManyMapper">
    <resultMap id="oneToMany" type="classes">
        <id column="cid" property="id"/>
        <result column="cname" property="name"/>
<!--        collection用于配置被包含的集合对象的映射关系,此处不能再使用association,
            association专用于一对一。而此处一个班级中可以有多个学生,是一对多的关系,是集合的范畴,应该用collection
            property:被包含对象的变量的名称
            ofType:被包含的对象额实际数据类型-->
        <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>

特别注意:

  • 一对一中用的association专用于一对一。而此处一个班级中可以有多个学生,是一对多的关系
  • 集合的范畴,应该用collection,collection用于配置被包含的集合对象的映射关系
  • collection常用的两个属性property:被包含对象的变量的名称;ofType:被包含的对象额实际数据类型,本程序中collection封装的是student集合,sql查询的图像如下
  • 在这里插入图片描述

功能实现

public class Test02 {

    @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 aClass : classes) {
            System.out.println(aClass.getId() + "," + aClass.getName());
            List<Student> students = aClass.getStudents(); //班级中有那些学生
            for (Student student : students) {
                System.out.println("\t" + student);
            }
        }

    }
}

在这里插入图片描述

小结

在这里插入图片描述

三、多对一操作

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

举报

相关推荐

0 条评论