Mybatis多表操作


前言

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映射文件的,自然就会找不到了

关于mybatis中起别名的问题

在主配置文件中使用如下代码

<!--起别名-->
    <typeAliases>
        <package name="com.ych.bean"/>
    </typeAliases>

优缺点:可以批量设置别名,一次性设置一个包内的实体类。但是不能自定义别名,别名一般与实体类名相同,但是不区分大小写。

二、一对多操作

数据库环境

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

    }
}

在这里插入图片描述

小结

在这里插入图片描述

补充:关于resultType和resultMap

基本映射 :(resultType)使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。(数据库,实体,查询字段,这些全部都得一一对应)高级映射 :(resultMap) 如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。(高级映射,字段名称可以不一致,通过映射来实现)

resultType和resultMap功能类似 ,都是返回对象信息 ,但是resultMap要更强大一些 ,可自定义。因为resultMap要配置一下,表和类的一一对应关系,所以说就算你的字段名和你的实体类的属性名不一样也没关系,都会给你映射出来,但是,resultType就比较鸡肋了,必须字段名一样,比如说 cId和c_id 这种的都不能映射 。

来源:https://www.jb51.net/article/190027.htm

三、多对多操作

数据库环境

CREATE TABLE course(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(20)
);
INSERT INTO course VALUES (NULL,'语文');
INSERT INTO course VALUES (NULL,'数学');


CREATE TABLE stu_cr(
	id INT PRIMARY KEY AUTO_INCREMENT,
	sid INT,
	cid INT,
	CONSTRAINT sc_fk1 FOREIGN KEY (sid) REFERENCES student(id),
	CONSTRAINT sc_fk2 FOREIGN KEY (cid) REFERENCES course(id)
);
INSERT INTO stu_cr VALUES (NULL,1,1);
INSERT INTO stu_cr VALUES (NULL,1,2);
INSERT INTO stu_cr VALUES (NULL,2,1);
INSERT INTO stu_cr VALUES (NULL,2,2);

使用stu_cr作为中间表完成多对多映射
在这里插入图片描述

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.table03.ManyToManyMapper">
    <resultMap id="manyToMany" type="student">
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
        <result column="sage" property="age"/>

        <collection property="courses" ofType="com.ych.bean.Course">
            <id column="cid" property="id"/>
            <result column="cname" property="name"/>
        </collection>
    </resultMap>
    <select id="selectAll" resultMap="manyToMany">
        SELECT sc.sid,s.`NAME` sname,s.age sage,sc.cid,c.`NAME` cname FROM student s,course c,stu_cr sc WHERE sc.sid=s.id AND sc.cid=c.id
    </select>
</mapper>

多表操作的重点在于xml的编写,多对多操作和一对多操作的xml编写较为类似,不同之处仅仅在于sql语句的编写。
在这里插入图片描述

功能实现

public class Test03 {

    @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接口的实现类对象
        ManyToManyMapper mapper = sqlSession.getMapper(ManyToManyMapper.class);
        //5、调用实现类的方法接受结果
        List<Student> studentList = mapper.selectAll();
        //6、处理结果
        for (Student student : studentList) {
            System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());
            List<Course> courses = student.getCourses();
            for (Course course : courses) {
                System.out.println("\t" + course);
            }
        }
    }
}

结果如下
在这里插入图片描述

难点

多对多操作的难点在于数据库中中间表的编写,以及sql语句的书写

SELECT sc.sid,s.`NAME` sname,s.age sage,sc.cid,c.`NAME` cname FROM student s,course c,stu_cr sc WHERE sc.sid=s.id AND sc.cid=c.id

在这里插入图片描述

总结

在这里插入图片描述
注意:

  • 一对一:在任意一方添加外键来关联对方的主键
  • 一对多:在多的一方添加外键来关联一的主键
  • 多对多:需要一张中间表,中间表至少有两个字段来关联两方的主键

补充——注解开发

记住这张表即可
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值