MyBatis学习(六)MyBatis关联映射之一对多映射
数据库中一对多通常使用主外键关联,外键应该在多方,即多方维护关系。
下面举一个简单实例来看看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.4(Mybatis学习笔记)关联映射
一.一对一 mybatis处理一对一主要通过<resultMap>中的<association>元素来处理. <association>元素主要使用方方式有两种: ...
- mybatis 学习六 MyBatis主配置文件
在定义sqlSessionFactory时需要指定MyBatis主配置文件: <bean id="sqlSessionFactory" class="org.myb ...
- (转)MyBatis框架的学习(五)——一对一关联映射和一对多关联映射
http://blog.csdn.net/yerenyuan_pku/article/details/71894172 在实际开发中我们不可能只是对单表进行操作,必然要操作多表,本文就来讲解多表操作中 ...
- MyBatis:学习笔记(3)——关联查询
MyBatis:学习笔记(3)--关联查询 关联查询 理解联结 SQL最强大的功能之一在于我们可以在数据查询的执行中可以使用联结,来将多个表中的数据作为整体进行筛选. 模拟一个简单的在线商品购物系统, ...
- (转)MyBatis框架的学习(六)——MyBatis整合Spring
http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...
- MyBatis 系列五 之 关联映射
MyBatis 系列五 之 关联映射 一对多的关联映射 一对多关联查询多表数据 1.1在MyBatis映射文件中做如下配置 <!--一对多单向的连接两表的查询--> <resultM ...
- mybatis学习笔记(7)-输出映射
mybatis学习笔记(7)-输出映射 标签: mybatis mybatis学习笔记7-输出映射 resultType 输出简单类型 输出pojo对象和pojo列表 resultMap result ...
- MyBatis学习总结-MyBatis快速入门的系列教程
MyBatis学习总结-MyBatis快速入门的系列教程 [MyBatis]MyBatis 使用教程 [MyBatis]MyBatis XML配置 [MyBatis]MyBatis XML映射文件 [ ...
- SSM框架开发web项目系列(三) MyBatis之resultMap及关联映射
前言 在上篇MyBatis基础篇中我们独立使用MyBatis构建了一个简单的数据库访问程序,可以实现单表的基本增删改查等操作,通过该实例我们可以初步了解MyBatis操作数据库需要的一些组成部分(配置 ...
随机推荐
- 使用Visual Studio 2017开发python,并在iis上部署Python Django
作为宇宙第一IDE,怎么可以不支持python开发呢? 1.Visual Studio Installer 扩展Python开发 开始菜单中打开Visual Studio Installer,点修改. ...
- 【Win10】zip安装MySQL
1. mysqld初始化时my.ini的第二个默认位置是%windir%/my.ini rem 1.查看此变量对应的目录,在此目录下编辑 my.ini,mysqld会自动找到 echo %WINDIR ...
- ThinkPHP系统变量,常量,序列化,反序列化,缓存
变量的输出: 在模板中输出一个变量有两种形式:{$list.name} {$list[‘name’]} 在模板中可以使用系统变量,以$Think.开头 系统变量:(举例选几个) 获得服务器的IP地址: ...
- Struts2使用小问题-NoSuchFieldException
五月 12, 2017 4:55:14 下午 com.opensymphony.xwork2.util.logging.jdk.JdkLogger warn 警告: couldn't clear to ...
- python注释方法以及编码问题
一.单行注释 在python中常使用"#"来进行单行注释,其快捷键为"ctrl+/",如果要对多行代码也就是代码块进行注释时,也可以选中多行按下 "c ...
- linux命令详解(一)netstat
今天在使用linux的时候,要查看端口号,但是不知道要使用哪一个命令所以就学习了一下,原来是使用netstat,接下来给大家一起来学习. 一.netstat介绍 1.1.简介 Netstat 命令用于 ...
- ehcache memcache redis 三大缓存对比
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt268 最近项目组有用到这三个缓存,去各自的官方看了下,觉得还真的各有千秋!今 ...
- Maven(一)初识Maven
前言 在这之前一直都有去看关于Maven的相关介绍,但是没有到真正要用的时候,自己总是以为懂了.其实真的感觉Maven并没有想象的那么简单! 那我们该怎么去学习maven呢?接下来我将从: 初步认识m ...
- 学习笔记GAN004:DCGAN main.py
Scipy 高端科学计算:http://blog.chinaunix.net/uid-21633169-id-4437868.html import os #引用操作系统函数文件 import sci ...
- Android学习记录:线程
在Java中,线程的建立方法如下. 新建一个类,接口Runnable,重载 run方法 import javax.swing.JTextField; public class test impleme ...