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

下面举一个简单实例来看看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. malloc/free 的使用要点

    函数malloc的原型如下: void * malloc(size_t size); 用malloc申请一块长度为length的整数类型的内存,程序如下: int   *p = (int *)mall ...

  2. Myeclipse详细使用教程

    Myeclipse详细使用教程.. /*+Shift+Enter(生成多行注释) /**+Shift+Enter(生成文档注释)-----------------问题:在编辑jsp的时候,如果光标移动 ...

  3. .NET Core+Selenium+Github+Travis CI => SiteHistory

    前言 总是三分钟热度的我折腾了一个可以每天自动截取指定网站页面并保存到Github的项目SiteHistory,感觉挺好(每次都这样). 想知道YouTube今天的首页长啥样么?点此查看 想知道You ...

  4. Servlet中Response对象应用2(输出随机验证码图片)

    预期结果如图: 可用于登陆界面的验证 需要使用random类和绘画相关的几个类.以及imageio的内容. import java.awt.*; import java.awt.image.Buffe ...

  5. TensorFlow框架(5)之机器学习实践

    1. Iris data set Iris数据集是常用的分类实验数据集,由Fisher, 1936收集整理.Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集.数据集包含150个数据集,分为3类, ...

  6. Openfire分析之二:主干程序分析

    引言 宇宙大爆炸,于是开始了万物生衍,从一个连人渣都还没有的时代,一步步进化到如今的花花世界. 然而沧海桑田,一百多亿年过去了-. 好复杂,但程序就简单多了,main()函数运行,敲个回车,一行Hel ...

  7. javaScript 设计模式系列之三:代理模式

    介绍 代理模式为其他对象提供一种代理以控制对这个对象的访问. 根据代理模式的使用目的不同,代理模式又可以分为多种类型: 远程代理(Remote Proxy) 虚拟代理(Virtual Proxy)如需 ...

  8. redi安装

    借鉴文章:https://segmentfault.com/a/1190000010709337 在linux中使用wget时,若报-bash: wget: command not found,则表明 ...

  9. Linux入门练习

    1.echo是用于终端打印的基本命令: 1.1echo默认将一个换行符追加到输出文本的尾部. 1.2 echo中转义换行符 如需使用转义序列,则采用echo -e "包含转义序列的字符串&q ...

  10. [知了堂学习笔记]_纯JS制作《飞机大战》游戏_第2讲(对象的实现及全局变量的定义)

    整体展示: 一.全局变量 /*===================玩家参数==========================*/ var myPlane; //英雄对象 var leftbtn = ...