数据库中一对多通常使用主外键关联,外键应该在多方,即多方维护关系。

下面举一个简单实例来看看MyBatis怎么处理一对多的关系。

1.创建一个项目,导入所需jar包,导入db.properties配置文件,导入log4j.properties配置文件

2.创建一个数据库,在里面创建两张表

-- Table structure for `t_clazz`
-- ----------------------------
DROP TABLE IF EXISTS `t_clazz`;
CREATE TABLE `t_clazz` (
`id` int(11) NOT NULL,
`code` varchar(18) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of t_clazz
-- ----------------------------
INSERT INTO `t_clazz` VALUES ('', '一班');
INSERT INTO `t_clazz` VALUES ('', '二班');
-- Table structure for `t_student`
-- ----------------------------
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(18) NOT NULL,
`sex` varchar(3) NOT NULL,
`age` int(11) NOT NULL,
`cid` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `cid` (`cid`),
CONSTRAINT `cid` FOREIGN KEY (`cid`) REFERENCES `t_clazz` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of t_student
-- ----------------------------
INSERT INTO `t_student` VALUES ('', '张三', '男', '', '');
INSERT INTO `t_student` VALUES ('', '李四', '男', '', '');
INSERT INTO `t_student` VALUES ('', '小红', '女', '', '');

3.编写对应的实体类

public class Student {

    private Integer id;
private String name;
private String sex;
private Integer age;
//关联的clazz对象
private Clazz clazz;
public class Clazz {

    private Integer id;
private String code;
//关联的student集合
private List<Student> students;

4.编写对应的SQL映射文件

ClazzMapper.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.dj.mapper.ClazzMapper"> <select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
select * from t_clazz where id =#{id}
</select>
<resultMap type="com.dj.domain.Clazz" id="clazzResultMap">
<id property="id" column="id"/>
<resultproperty="code" column="code"/>
<!--property表示返回类型Clazz的属性students
column表示将id作为参数进行之后的查询
fetchtype表示懒加载
javaType表示属性对应的类型
ofType表示集合当中的类型
-->
<collection property="students" column="id" fetchType="lazy"
javaType="ArrayList" ofType="com.dj.domain.Student"
select="com.dj.mapper.StudentMapper.selectStudentByClazzId">
<id property="id" column="id"/>
<resultproperty="name" column="name"/>
<resultproperty="sex" column="sex"/>
<resultproperty="age" column="age"/>
</collection>
</resultMap> </mapper>

StudentMapper.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 namespace="com.dj.mapper.StudentMapper"> <select id="selectStudentByClazzId" parameterType="int" resultType="com.dj.domain.Student">
select * from t_student where cid=#{id}
</select>
</mapper>

5.编写mybatis-config.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>
<!-- 引入 外部db.properties文件-->
<properties resource="db.properties"/>
<!-- 指定 MyBatis 所用日志的具体实现-->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<!-- 环境配置 -->
<environments default="mysql">
<environment id="mysql">
<!-- 指定事务类型 -->
<transactionManager type="JDBC"/>
<!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- SQL映射文件位置 -->
<mappers>
<mapper resource="com/dj/mapper/StudentMapper.xml"/>
<mapper resource="com/dj/mapper/ClazzMapper.xml"/>
</mappers>
</configuration>

6.mybatis建议通过mapper接口的代理对象访问mybatis,该对象关联了一个sqlsession对象,开发者可以通过该对象直接调用方法操作数据库。

注意: mapper接口对象的类名必须和之前的mapper.xml的namespace一致,方法名和参数名及返回类型也要与mapper.xml的配置一致。

public interface ClazzMapper {
//根据id查询班级信息
Clazz selectClazzById(int id); }

7.测试

public class OneToManyTest {

    public static void main(String[] args) throws Exception {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获得mapper接口的代理对象
ClazzMapper mapper = sqlSession.getMapper(ClazzMapper.class);
//调用接口中的方法
Clazz clazz = mapper.selectClazzById(1);
List<Student> students = clazz.getStudents();
for (Student student : students) {
System.out.println(student);
} } }

在控制台可以看到如下结果:

测试成功。

MyBatis学习(六)MyBatis关联映射之一对多映射的更多相关文章

  1. 1.4(Mybatis学习笔记)关联映射

    一.一对一 mybatis处理一对一主要通过<resultMap>中的<association>元素来处理. <association>元素主要使用方方式有两种: ...

  2. mybatis 学习六 MyBatis主配置文件

    在定义sqlSessionFactory时需要指定MyBatis主配置文件: <bean id="sqlSessionFactory" class="org.myb ...

  3. (转)MyBatis框架的学习(五)——一对一关联映射和一对多关联映射

    http://blog.csdn.net/yerenyuan_pku/article/details/71894172 在实际开发中我们不可能只是对单表进行操作,必然要操作多表,本文就来讲解多表操作中 ...

  4. MyBatis:学习笔记(3)——关联查询

    MyBatis:学习笔记(3)--关联查询 关联查询 理解联结 SQL最强大的功能之一在于我们可以在数据查询的执行中可以使用联结,来将多个表中的数据作为整体进行筛选. 模拟一个简单的在线商品购物系统, ...

  5. (转)MyBatis框架的学习(六)——MyBatis整合Spring

    http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...

  6. MyBatis 系列五 之 关联映射

    MyBatis 系列五 之 关联映射 一对多的关联映射 一对多关联查询多表数据 1.1在MyBatis映射文件中做如下配置 <!--一对多单向的连接两表的查询--> <resultM ...

  7. mybatis学习笔记(7)-输出映射

    mybatis学习笔记(7)-输出映射 标签: mybatis mybatis学习笔记7-输出映射 resultType 输出简单类型 输出pojo对象和pojo列表 resultMap result ...

  8. MyBatis学习总结-MyBatis快速入门的系列教程

    MyBatis学习总结-MyBatis快速入门的系列教程 [MyBatis]MyBatis 使用教程 [MyBatis]MyBatis XML配置 [MyBatis]MyBatis XML映射文件 [ ...

  9. SSM框架开发web项目系列(三) MyBatis之resultMap及关联映射

    前言 在上篇MyBatis基础篇中我们独立使用MyBatis构建了一个简单的数据库访问程序,可以实现单表的基本增删改查等操作,通过该实例我们可以初步了解MyBatis操作数据库需要的一些组成部分(配置 ...

随机推荐

  1. Zepto源码分析(一)核心代码分析

    本文只分析核心的部分代码,并且在这部分代码有删减,但是不影响代码的正常运行. 目录 * 用闭包封装Zepto * 开始处理细节 * 正式处理数据(获取选择器选择的DOM) * 正式处理数据(添加DOM ...

  2. 【Eclipse】更改部署位置

    在使用eclipse启动tomcat时,偶尔会遇到应用没被部署的现象,导致访问时出现404 问题原因:应用部署在了eclipse自带的webapps中. 我们通常不喜欢eclipse自带的tomcat ...

  3. 8.13.2 TreeSet实现Comparable接口的两种方式

    推荐使用第二种方式,编写比较器可以使数据类的程序耦合度降低,同时比较器也可以重复利用! 第一种方式:数据类实现Comparable接口,实现其中的compareTo方法 创建对象时,使用TreeSet ...

  4. JS针对pc页面固定宽度在手机展示问题 <meta ...>

    结合一些 网上大神级前端作品的 介绍 修改了一下自己的代码  做出了一个相对简单的缩放代码 1. <meta name="viewport" content="wi ...

  5. ASP.NET Core MVC – Tag Helper 组件

    ASP.NET Core Tag Helpers系列目录,这是第五篇,共五篇: ASP.NET Core MVC – Tag Helpers 介绍 ASP.NET Core MVC – Caching ...

  6. Struts:文件上传下载

  7. 6.26学习 异步委托回调函数 VS 多线程 VS 并行处理

    描述: 我现在是轮询着构建实例,然后这个实例去执行一个方法,但是执行方法需要大约10s时间,全部轮询下来需要很长时间.所以我现在要更改,头给了我两个方法,1多线程 2异步委托回调函数. 异步委托回调函 ...

  8. Linux下C/C++和lua交互-Table

    本来这些文章都是在我的个人网站www.zhangyi.studio,目前处在备案状态,暂时访问不了,所以搬到这边.  最近这两天需要弄清楚C++和lua间相互调用和数据传递,废话不多说,直接上过程. ...

  9. window 使用git 非ssh key 面密码登录

    Windows下使用git bash时,总是提示输入用户名密码,严重影响了开发效率,经搜索查找找到了如下有效的解决方案,屡试不爽! 1.先创建存储用户名密码的文件 ,在home文件夹,一般是 C:\D ...

  10. 微信H5支付:网络环境未能通过安全验证,请稍后再试。解决办法(PHP版)

    前(tu)言(cao) (这段前言纯属吐槽,着急解决问题的小伙伴,赶紧看正文吧) 最近做了支付宝和微信支付,先做的是PC端网站的支付,就是出个二维码,然后手机扫描支付,当然支付宝在扫码页面支持登录支付 ...