JavaEE_09_Mybatis级联映射

本文详细介绍了如何在Mybatis中实现对象关系的级联映射,包括对多(collection)和对一(association)操作。通过Teacher与Student实体类的关系,展示了在Mapper和XML配置文件中的映射设置,以及在Service和Controller层的调用方法,提供了一对多和一对多查询的完整示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《Mybatis级联映射》

目录

  • 对象关系(掌握)
  • 对多操作(熟练)
  • 对一操作(熟练)

一、对象关系

表与表之间主要有四种关系:一对一多对一一对多多对多

Mybatis提供了两个标签实现这种关系:association(对一),collection(对多)。

请添加图片描述

二、对多操作

  1. com.hpr.entity.Teacher
...
public class Teacher {
    ...
        
    //一个老师对应多个学生
    private List<Student> students;

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
}
  1. com.hpr.mapper.TeacherMapper
...
public interface TeacherMapper {
    ...
    List<Teacher> testToMany();
}
  1. mappers/TeacherMappper.xml
<!-- 外键结果映射 -->
<resultMap id="FkResultMap" type="com.hpr.entity.Teacher">
    <id column="teacher_id" property="teacherId"/>
    <result column="teacher_name" property="teacherName"/>
    <result column="age" property="age"/>
    <result column="phone_number" property="phoneNumber"/>
    <result column="info" property="info"/>
    <!-- 对多 -->
    <collection property="students" resultMap="com.hpr.mapper.StudentMapper.BaseResultMap"/>
</resultMap>

...

<!-- 测试一对多 -->
<select id="testToMany" resultMap="FkResultMap">
    select *
    from teacher t,
         student s
    where t.teacher_id = s.teacher_id
</select>
  1. com.hpr.service.ITeacherService
...
public interface ITeacherService {
    ...
    Response<List<Teacher>> testToMany();

}
  1. com.hpr.service.impl.TeacherService
public class TeacherService implements ITeacherService {

    @Override
    public Response<List<Teacher>> testToMany() {
        return new Response<>(200, "success", teacherMapper.testToMany());
    }
}
  1. com.hpr.controller.MybatisController
...
public class MybatisController {
    ...
    @GetMapping("/testToMany")
    @ApiOperation("测试对多")
    public Response<List<Teacher>> testToMany() {
        return iTeacherService.testToMany();
    }
}
  1. 启动测试

请添加图片描述

执行结果

请添加图片描述

三、对一操作

  1. com.hpr.entity.Student
...
public class Student {
    ...
        
    //一个学生对应一个老师
    private Teacher teacher;

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }
}
  1. com.hpr.mapper.StudentMapper
...
@Repository
public interface StudentMapper {
    ...
    List<Student> testToOne();
}
  1. mappers/StudentMappper.xml
<!-- 外键结果映射 -->
<resultMap id="FkResultMap" type="com.hpr.entity.Student">
    <id column="student_id" property="studentId"/>
    <result column="student_name" property="studentName"/>
    <result column="chinese" property="chinese"/>
    <result column="math" property="math"/>
    <result column="english" property="english"/>
    <result column="teacher_id" property="teacherId"/>
    <!-- 对一 -->
    <association property="teacher" resultMap="com.hpr.mapper.TeacherMapper.BaseResultMap"/>
</resultMap>

...

<select id="testToOne" resultMap="FkResultMap">
    select *
    from student s,
         teacher t
    where s.teacher_id = t.teacher_id
</select>
  1. com.hpr.service.IStudentService
...
public interface IStudentService {
    ...
    Response<List<Student>> testToOne();
}
  1. com.hpr.service.impl.StudentService
...
@Service
public class StudentService implements IStudentService {

    @Autowired
    private StudentMapper studentMapper;

    ...
    @Override
    public Response<List<Student>> testToOne() {
        return new Response<>(200, "success", studentMapper.testToOne());
    }
}
  1. com.hpr.controller.MybatisController
...
public class MybatisController {
    ...
    @GetMapping("/testToOne")
    @ApiOperation("测试对一")
    public Response<List<Student>> testToOne() {
        return iStudentService.testToOne();
    }
}
  1. 启动测试

请添加图片描述

执行结果

请添加图片描述

总结

重点

  1. 数据库表关系判断;
  2. “对多”、“对一”实现手段。

难点

  1. “对多”、“对一”实现手段。
### Java EEMyBatis 实验模块缺失解决方案 在处理 Java EEMyBatis 实验过程中,如果遇到模块丢失的问题,通常可以从以下几个方面进行排查和修复: #### 1. **确认项目依赖配置** 确保项目的 `pom.xml` 文件(如果是 Maven 项目)或者 Gradle 构建文件中已经正确引入了 MyBatis 及其相关依赖项。以下是典型的 Maven 配置示例[^1]: ```xml <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> ``` 如果没有正确配置上述依赖,则可能导致 MyBatis 功能无法正常加载。 --- #### 2. **检查实验环境设置** 验证当前使用的开发工具是否支持所需的 MyBatis 版本以及对应的 JDK 和服务器版本。例如,在 Eclipse 开发环境中,需确保已安装并启用了必要的插件,比如 MyBatis Generator 插件或类似的辅助工具[^3]。 此外,还需注意以下几点: - 数据库驱动程序是否匹配目标数据库类型。 - 是否存在路径错误或其他外部资源配置问题。 --- #### 3. **分析日志信息** 当运行应用程序时发生异常,应仔细查看控制台输出的日志消息。通过捕获到的关键字定位具体原因。例如,某些情况下可能是由于 SQL 映射文件未被识别而导致的功能失效[^4]。 对于此类情况,建议重新整理 Mapper 接口及其 XML 文件之间的关联关系,并按照如下方式注册至 Spring 容器中: ```java @Configuration @MapperScan(basePackages = "com.example.mapper") // 替换为实际包名 public class MyBatisConfig { } ``` --- #### 4. **恢复缺失的模块** 如果确实发现某个特定功能模块遗失,可以通过以下途径尝试找回: - 查阅官方文档获取最新版教程资料; - 对比其他成功案例寻找差异之处; - 利用版本控制系统(如 Git),回滚至上一次稳定状态后再逐步调整修改部分直至满足需求为止。 同时提醒开发者定期备份重要代码片段以防意外删除操作带来的不便影响整体进度安排。 --- #### 5. **测试与调试** 最后一步便是执行全面详尽的功能性检测工作流程以确保存在的所有潜在隐患均已被妥善消除掉之后再提交最终成果物给相关人员审阅批准发布上线投入使用环节当中去吧! ```java // 测试样例 @Test void testMyBatisFunctionality() { SqlSession session = sqlSessionFactory.openSession(); try { User user = session.selectOne("getUser", 1); assertNotNull(user); // 断言对象不为空 } finally { session.close(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值