MyBatis一对一关联查询

一对一级联关系在现实生活中是十分常见的,例如一个大学生只有一个学号,一个学号只属于一个学生。同样,人与身份证也是一对一的级联关系。

在 MyBatis 中,通过 <resultMap> 元素的子元素 <association> 处理一对一级联关系。示例代码如下。

<association property="studentCard" column="cardId"
             javaType="net.biancheng.po.StudentCard"
             select="net.biancheng.mapper.StudentCardMapper.selectStuCardById" />
                

在 <association> 元素中通常使用以下属性。

  • 一对多的关系,如角色和用户的关系。通俗的理解就是,一家软件公司会存在许多软件工程师,公司和软件工程师就是一对多的关系。

  • 一对一的关系。每个软件工程师都有一个编号(ID),这是他在公司的标识,它与工程师是一对一的关系。

  • 多对多的关系,有些公司一个角色可以对应多个用户,但是一个用户可以兼任多个角色。通俗的说,一个人既可以是总经理,同时也是技术总监,而技术总监这个职位可以对应多个人,这就是多对多的关系。

实际应用中,由于多对多的关系比较复杂,会增加理解和关联的复杂度,所以应用较少。推荐的方法是,用一对多的关系把它分解为双向关系,以降低关系的复杂度,简化程序。具体操作方法可以参考《MyBatis多对多关联查询》一节。

级联的优点是获取关联数据十分便捷。但是级联过多会增加系统的复杂度,同时降低系统的性能,此增彼减。所以记录超过 3 层时,就不要考虑使用级联了,因为这样会造成多个对象的关联,导致系统的耦合、负载和难以维护。

本教程分为 3 节对 MyBatis 的级联关系进行详细讲解,小伙伴们请点击下方链接阅读学习。

  • property:指定映射到实体类的对象属性。

  • column:指定表中对应的字段(即查询返回的列名)。

  • javaType:指定映射到实体对象属性的类型。

  • select:指定引入嵌套查询的子 SQL 语句,该属性用于关联映射中的嵌套查询。

一对一关联查询可采用以下两种方式:

  • 单步查询,通过关联查询实现

  • 分步查询,通过两次或多次查询,为一对一关系的实体 Bean 赋值

示例

下面以学生和学号为例讲解一对一关联查询的处理过程。

1)创建数据表

创建 student(学生)和 studentcard(学号)数据表,SQL 语句如下。

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
  `sex` tinyint(4) DEFAULT NULL,
  `cardId` int(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `cardId` (`cardId`),
  CONSTRAINT `student_ibfk_1` FOREIGN KEY (`cardId`) REFERENCES `studentcard` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

insert  into `student`(`id`,`name`,`sex`,`cardId`) values (1,'C语言中文网',0,1),(2,'编程帮',0,2),(3,'赵小红',1,3),(4,'李晓明',0,4),(5,'李紫薇',1,5),(6,'钱百百',0,NULL);

DROP TABLE IF EXISTS `studentcard`;

CREATE TABLE `studentcard` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `studentId` int(20) DEFAULT NULL,
  `startDate` date DEFAULT NULL,
  `endDate` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `studentId` (`studentId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

insert  into `studentcard`(`id`,`studentId`,`startDate`,`endDate`) values (1,20200311,'2021-03-01','2021-03-11'),(2,20200314,'2021-03-01','2021-03-11'),(3,20200709,'2021-03-01','2021-03-11'),(4,20200508,'2021-03-01','2021-03-11'),(5,20207820,'2021-03-01','2021-03-11');
                

2)创建持久化类

在 myBatisDemo 应用的 net.biancheng.po 包下创建数据表对应的持久化类 Student 和 StudentCard。

Student 的代码如下:

package net.biancheng.po;

public class Student {
    private int id;
    private String name;
    private int sex;

    private StudentCard studentCard;

    /*省略setter和getter方法*/

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", studentCard=" + studentCard + "]";
    }
}
                

StudentCard 的代码如下:

package net.biancheng.po;

import java.util.Date;

public class StudentCard {
    private int id;
    private int studentId;
    private Date startDate;
    private Date endDate;

    /*省略setter和getter方法*/

    @Override
    public String toString() {
        return "StudentCard [id=" + id + ", studentId=" + studentId + "]";
    }
}
                

分步查询

新建 StudentCardMapper 类,代码如下。

package net.biancheng.mapper;
import net.biancheng.po.StudentCard;
public interface StudentCardMapper {
    public StudentCard selectStuCardById(int id);
}
                

StudentCardMapper.xml 对应映射 SQL 语句代码如下。

<mapper namespace="net.biancheng.mapper.StudentCardMapper">
    <select id="selectStuCardById"
            resultType="net.biancheng.po.StudentCard">
        SELECT * FROM studentCard WHERE id = #{id}
    </select>
</mapper>
                

StudentMapper 类方法代码如下。

package net.biancheng.mapper;
import net.biancheng.po.Student;
public interface StudentMapper {
    public Student selectStuById1(int id);
    public Student selectStuById2(int id);
}
                

StudentMapper.xml 代码如下。

<mapper namespace="net.biancheng.mapper.StudentMapper">
    <!-- 一对一根据id查询学生信息:级联查询的第一种方法(嵌套查询,执行两个SQL语句) -->
    <resultMap type="net.biancheng.po.Student" id="cardAndStu1">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="sex" column="sex" />
        <!-- 一对一级联查询 -->
        <association property="studentCard" column="cardId"
                     javaType="net.biancheng.po.StudentCard"
                     select="net.biancheng.mapper.StudentCardMapper.selectStuCardById" />
    </resultMap>
    <select id="selectStuById1" parameterType="Integer"
            resultMap="cardAndStu1">
        select * from student where id=#{id}
    </select>
</mapper>
                

测试代码如下。

public class Test {
    public static void main(String[] args) throws IOException {
        InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
        SqlSession ss = ssf.openSession();

        Student stu = ss.getMapper(StudentMapper.class).selectStuById1(2);
        System.out.println(stu);
    }
}
                

运行结果如下。

DEBUG [main] - ==>  Preparing: select * from student where id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - ====>  Preparing: SELECT * FROM studentCard WHERE id = ?
DEBUG [main] - ====> Parameters: 2(Integer)
DEBUG [main] - <====      Total: 1
DEBUG [main] - <==      Total: 1
Student [id=2, name=编程帮, sex=0, studentCard=StudentCard [id=2, studentId=20200314]]
                

单步查询

在 StudentMapper.xml 中添加以下代码。

<resultMap type="net.biancheng.po.Student" id="cardAndStu2">
    <id property="id" column="id" />
    <result property="name" column="name" />
    <result property="sex" column="sex" />
    <!-- 一对一级联查询 -->
    <association property="studentCard"
                 javaType="net.biancheng.po.StudentCard">
        <id property="id" column="id" />
        <result property="studentId" column="studentId" />
    </association>
</resultMap>
<select id="selectStuById2" parameterType="Integer"
        resultMap="cardAndStu2">
    SELECT s.*,sc.studentId FROM student s,studentCard sc
    WHERE
    s.cardId = sc.id AND s.id=#{id}
</select>
                

在 StudentMapper 中添加以下方法。

public Student selectStuById2(int id);
                

运行结果如下。

DEBUG [main] - ==>  Preparing: SELECT s.*,sc.studentId FROM student s,studentCard sc WHERE s.cardId = sc.id AND s.id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <==      Total: 1
Student [id=2, name=编程帮, sex=0, studentCard=StudentCard [id=2, studentId=20200314]]