Mybatis 复杂结果映射(ResultMap) - 一对一关系映射

上一篇内容我们介绍了Mybatis使用复杂的结果映射解决一对多关系中复杂的数据映射问题,本篇我们继续介绍使用复杂的结果映射解决一对一关系中复杂的数据映射问题。

如果您对普通结果映射不太了解,可以先学习和了解:

Mybatis 复杂结果映射(ResultMap) - 一对多关系映射icon-default.png?t=N7T8https://blog.csdn.net/m1729339749/article/details/132533523

一、准备数据

这里我们直接使用脚本初始化数据库中的数据

-- 如果数据库不存在则创建数据库
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切换数据库
USE demo;
-- 创建班级表
CREATE TABLE IF NOT EXISTS T_CLASS(
  ID INT PRIMARY KEY,
  CLASS_NAME VARCHAR(32) NOT NULL
);
-- 创建学生表
CREATE TABLE IF NOT EXISTS T_STUDENT(
  ID INT PRIMARY KEY,
  USERNAME VARCHAR(32) NOT NULL,
  AGE INT NOT NULL,
  CLASS_ID INT NOT NULL
);
-- 插入班级数据
INSERT INTO T_CLASS(ID, CLASS_NAME)
VALUES(1, '班级1'),(2, '班级2');
-- 插入学生数据
INSERT INTO T_STUDENT(ID, USERNAME, AGE, CLASS_ID)
VALUES(1, '张三', 20, 1),(2, '李四', 22, 2),(3, '王五', 24, 1),(4, '赵六', 26, 2),(5, '田七', 21, 2);

 创建了一个名称为demo的数据库;并在库里创建了名称为T_CLASS的班级表和名称为T_STUDENT的学生表,并向表中插入了数据

二、定义实体类

在cn.horse.demo包下创建ClassInfo、StudentInfo实体类

为了方便打印用户的信息这里重写了ToString()方法

ClassInfo实体类:

package cn.horse.demo;

public class ClassInfo {

    private String id;
    private String name;

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append('{');
        result.append("id: " + this.id);
        result.append(", ");
        result.append("name: " + this.name);
        result.append('}');
        return result.toString();
    }
}

StudentInfo实体类: 类中包含了一个ClassInfo对象

package cn.horse.demo;

public class StudentInfo {
    private int id;
    private String name;
    private int age;
    private ClassInfo classInfo;

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append('{');
        result.append("id: " + this.id);
        result.append(", ");
        result.append("name: " + this.name);
        result.append(", ");
        result.append("age: " + this.age);
        result.append(", ");
        result.append("classInfo: " + this.classInfo.toString());
        result.append('}');
        return result.toString();
    }
}

从上面定义的实体类看来,StudentInfo与ClassInfo之间是一对一的关系

三、内嵌映射

这里我在resources下创建了一个demo的目录,并在目录下创建了一个StudentInfoMapper1.xml的配置文件。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.StudentInfoMapper1">

    <resultMap id="studentInfoMap" type="cn.horse.demo.StudentInfo">
        <result column="ID" property="id" />
        <result column="NAME" property="name" />
        <result column="AGE" property="age" />
        <association property="classInfo" javaType="cn.horse.demo.ClassInfo">
            <result column="CLASS_ID" property="id" />
            <result column="CLASS_NAME" property="name" />
        </association>
    </resultMap>

    <select id="findAll" resultMap="studentInfoMap">
        SELECT
            s.ID ID,
            s.USERNAME NAME,
            s.AGE AGE,
            c.ID CLASS_ID,
            c.CLASS_NAME CLASS_NAME
        FROM T_STUDENT s, T_CLASS c
        WHERE s.CLASS_ID = c.ID
    </select>
</mapper>

findAll 查询标签用于关联查询学生和班级表,查询的结果使用studentInfoMap进行映射成StudentInfo实例;

classInfo字段的映射使用了association标签,此标签用于解决一对一的关联关系的数据映射问题。通过使用javaType指定对象的映射类型,并在association标签内配置数据库表字段与类型字段的映射关系,就可以完成数据的映射。

另外,还需要在mybatis-config中配置StudentInfoMapper1.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="org.gjt.mm.mysql.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;useSSL=false&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="horse"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="demo/StudentInfoMapper1.xml" />
    </mappers>
</configuration>

测试:

package cn.horse.demo;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;
import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        findAll("cn.horse.demo.StudentInfoMapper1.findAll");
    }

    private static void findAll(String statement) {
        // 读取mybatis配置文件
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
        // 根据配置创建SqlSession工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);

        SqlSession sqlSession = null;
        try {
            // 创建SqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 查询学生列表
            List<StudentInfo> studentInfoList = sqlSession.selectList(statement);
            for (StudentInfo studentInfo: studentInfoList) {
                System.out.println(studentInfo);
            }
        } finally {
            // 关闭会话
            if(Objects.nonNull(sqlSession)) {
                sqlSession.close();
            }
        }
    }
}

 代码执行的结果如下:

四、resultMap映射

这里我在resources的demo目录下创建了一个StudentInfoMapper2.xml的配置文件。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.StudentInfoMapper2">

    <resultMap id="studentInfoMap" type="cn.horse.demo.StudentInfo">
        <result column="ID" property="id" />
        <result column="NAME" property="name" />
        <result column="AGE" property="age" />
        <association property="classInfo" resultMap="classInfoMap" />
    </resultMap>

    <resultMap id="classInfoMap" type="cn.horse.demo.ClassInfo">
        <result column="CLASS_ID" property="id" />
        <result column="CLASS_NAME" property="name" />
    </resultMap>

    <select id="findAll" resultMap="studentInfoMap">
        SELECT
            s.ID ID,
            s.USERNAME NAME,
            s.AGE AGE,
            c.ID CLASS_ID,
            c.CLASS_NAME CLASS_NAME
        FROM T_STUDENT s, T_CLASS c
        WHERE s.CLASS_ID = c.ID
    </select>
</mapper>

findAll 查询标签用于关联查询班级和学生表,查询的结果使用studentInfoMap进行映射成StudentInfo实例;

classInfo字段的映射使用了association标签,此标签用于解决一对一的关联关系的数据映射问题。通过使用resultMap指定对象的结果映射,完成对象的数据映射

另外,还需要在mybatis-config中配置StudentInfoMapper2.xml文件

<mapper resource="demo/StudentInfoMapper2.xml" />

测试:

findAll("cn.horse.demo.StudentInfoMapper2.findAll");

代码执行的结果如下:

五、select结果集

这里我在resources的demo目录下创建了一个StudentInfoMapper3.xml的配置文件。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.StudentInfoMapper3">

    <resultMap id="studentInfoMap" type="cn.horse.demo.StudentInfo">
        <result column="ID" property="id" />
        <result column="NAME" property="name" />
        <result column="AGE" property="age" />
        <association property="classInfo" column="CLASS_ID" select="findById" />
    </resultMap>

    <resultMap id="classInfoMap" type="cn.horse.demo.ClassInfo">
        <result column="ID" property="id" />
        <result column="CLASS_NAME" property="name" />
    </resultMap>

    <select id="findAll" resultMap="studentInfoMap">
        SELECT
            ID,
            USERNAME NAME,
            AGE,
            CLASS_ID
        FROM T_STUDENT
    </select>

    <select id="findById" resultMap="classInfoMap">
        SELECT
            ID,
            CLASS_NAME
        FROM T_CLASS
        WHERE ID = #{id}
    </select>
</mapper>

findAll 查询标签用于关联查询班级和学生表,查询的结果使用studentInfoMap进行映射成StudentInfo实例;

classInfo字段的映射使用了association标签,此标签用于解决一对一的关联关系的数据映射问题。通过使用select指定查询标签执行的结果作为映射的数据,查询标签传递的参数使用column属性指定(此属性值来源于数据库表查询字段,示例中我们使用了数据库查询结果中的CLASS_ID字段作为参数进行查询学生的班级数据)。

另外,还需要在mybatis-config中配置StudentInfoMapper3.xml文件

<mapper resource="demo/StudentInfoMapper3.xml" />

测试:

findAll("cn.horse.demo.StudentInfoMapper3.findAll");

代码执行的结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
resultMap一对一MyBatis框架中的一种映射关系配置方式,用于将查询结果映射到一个Java对象上。在一对一映射中,查询结果中的每一行数据都会映射到一个Java对象上,实现了数据库表与Java对象的一一对应关系。 在MyBatis中,可以通过resultMap元素来定义一对一映射关系。以下是resultMap一对一的配置方式: 1. 首先,在mapper.xml文件中定义resultMap元素,并指定id和type属性,分别表示resultMap的唯一标识和映射的Java对象类型。 2. 在resultMap元素内部,使用id标签定义主键字段的映射关系,使用result标签定义其他字段的映射关系。 3. 对于关联的对象,可以使用association标签定义其映射关系。association标签内部可以使用id标签定义主键字段的映射关系,使用result标签定义其他字段的映射关系。 4. 最后,在select语句中使用resultMap属性指定要使用的resultMap。 示例代码如下: ```xml <resultMap id="userResultMap" type="com.example.User"> <id property="id" column="user_id"/> <result property="username" column="username"/> <result property="email" column="email"/> <association property="role" javaType="com.example.Role"> <id property="id" column="role_id"/> <result property="name" column="role_name"/> </association> </resultMap> <select id="getUser" resultMap="userResultMap"> SELECT u.id as user_id, u.username, u.email, r.id as role_id, r.name as role_name FROM users u INNER JOIN roles r ON u.role_id = r.id WHERE u.id = #{id} </select> ``` 以上示例中,resultMap定义了User对象与Role对象的一对一映射关系。在查询语句中,使用resultMap属性指定了要使用的resultMap
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值