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操作数据库需要的一些组成部分(配置 ...
随机推荐
- 第48篇 字符编码探密--ASCII,UTF8,GBK,Unicode
原文地址:http://blog.laofu.online/2017/08/22/encode-string/ ASCII 的由来 在计算机的“原始社会”,有人想把日常的使用的语言使用计算机来表示, ...
- 常用业务接口界面化 in python flask
背景: 对于业务测试来说,有一些基础业务接口是需要经常调用的,如根据userId查询某人的信息,修改某人的xx属性,一般的接口都有验签(或者说token)机制,使用postman等工具的话,也是需要去 ...
- AngularJS 动画总结
对读过的几篇文章的总结,尽量保证逻辑性,不断补充.精简.更正. 后面会列出参考文章地址,方便以后取用.感谢各位作者以及翻译者. AngularJS 动画思考 一.如何使用 1)我们需要构建什么 2)如 ...
- Python3使用Print输出带颜色字体
Phton3使用print输出带颜色的彩色字体 实现过程: 终端的字符颜色是用转义序列控制的,是文本模式下的系统显示功能,和具体的语言无关. 转义序列是以ESC开头,即用\03 ...
- vue-cli脚手架npm相关文件解读(7)dev-server.js
系列文章传送门: 1.build/webpack.base.conf.js 2.build/webpack.prod.conf.js 3.build/webpack.dev.conf.js 4.bui ...
- 为Ext添加下拉框和日期组件
Ext.onReady(function(){ var config = { fields:['module'], data:[['新建'],['删除'],['增加']}; var store = n ...
- JQ在线引用地址
1.7.2版本 百度的引用地址: <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js">< ...
- Scala中柯里化函数
高阶函数转一阶函数: val add1 = (x: Int) => x + 5 def add2(x: Int)(y: Int) = x + y //传入一个参数转换为一阶函数 def add3 ...
- win10下移动硬盘位置不可用无法访问
win10下移动硬盘位置不可用无法访问 网上搜索得到的答案是: 请参考以下步骤解决: 1.按Windows+R输入"CHKDSK H: /F /R"(H:是硬盘所在盘符./R 找到 ...
- CloseableHttpClient 源码
public abstract class CloseableHttpClient implements HttpClient, Closeable { private final Log log = ...