上一篇内容我们介绍了Mybatis使用复杂的结果映射解决一对多关系中复杂的数据映射问题,本篇我们继续介绍使用复杂的结果映射解决一对一关系中复杂的数据映射问题。
如果您对普通结果映射不太了解,可以先学习和了解:
Mybatis 复杂结果映射(ResultMap) - 一对多关系映射https://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&useSSL=false&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");
代码执行的结果如下: