实际项目中也存在很多的一对多的情况,下面看看这个简单的例子

table.sql

 CREATE TABLE tb_clazz(
id INT PRIMARY KEY AUTO_INCREMENT,
CODE VARCHAR(18),
NAME VARCHAR(18)
); INSERT INTO tb_clazz(CODE,NAME) VALUES('w5','五年级'); CREATE TABLE tb_student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(18),
sex VARCHAR(18),
age INT,
clazz_id INT,
FOREIGN KEY (clazz_id) REFERENCES tb_clazz(id)
); INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('张三','男',13,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('李四','女',14,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('王五','男',13,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('赵六','女',12,1);

创建一个Clazz对象和一个Student对象分别映射tb_clazz和tb_student表。班级和学生是一对多的关系,即一个班级可以有很多个学生,在Clazz类定义了一个student属性,该属性是一个List集合,用来映射一对多的关联关系,表示一个班级有多个学生

学生和班级是多对一的关系,即一个学生只属于一个班级,在student类当中定义一个clazz属性,该属性是一个Clazz类型,用来映射 多对一的关联关系,表示该学生所属的班级

Clazz.java

public class Clazz implements Serializable {

    private Integer id; // 班级id,主键
private String code; // 班级编号
private String name; // 班级名称 // 班级和学生是一对多的关系,即一个班级可以有多个学生
private List<Student> students;
}

Student.java

public class Student implements Serializable {
private Integer id; // 学生id,主键
private String name; // 姓名
private String sex; // 性别
private Integer age; // 年龄 // 学生和班级是多对一的关系,即一个学生只属于一个班级
private Clazz clazz;
}

xml文件的配置

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">
<!-- namespace指用户自定义的命名空间。 -->
<mapper namespace="com.rookie.bigdata.mapper.ClazzMapper"> <!-- 根据id查询班级信息,返回resultMap -->
<select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
SELECT * FROM tb_clazz WHERE id = #{id}
</select> <!-- 映射Clazz对象的resultMap -->
<resultMap type="com.rookie.bigdata.domain.Clazz" id="clazzResultMap">
<id property="id" column="id"/>
<result property="code" column="code"/>
<result property="name" column="name"/>
<!-- 一对多关联映射:collection fetchType="lazy"表示懒加载 -->
<collection property="students" javaType="ArrayList"
column="id" ofType="com.rookie.bigdata.domain.Student"
select="com.rookie.bigdata.mapper.StudentMapper.selectStudentByClazzId"
fetchType="lazy">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="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.rookie.bigdata.mapper.StudentMapper"> <!-- 根据id查询学生信息,多表连接,返回resultMap -->
<select id="selectStudentById" parameterType="int" resultMap="studentResultMap">
SELECT * FROM tb_clazz c,tb_student s
WHERE c.id = s.clazz_id
AND s.id = #{id}
</select> <!-- 根据班级id查询学生信息,返回resultMap -->
<select id="selectStudentByClazzId" parameterType="int"
resultMap="studentResultMap">
SELECT * FROM tb_student WHERE clazz_id = #{id}
</select> <!-- 映射Student对象的resultMap -->
<resultMap type="com.rookie.bigdata.domain.Student" id="studentResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<!-- 多对一关联映射:association -->
<association property="clazz" javaType="com.rookie.bigdata.domain.Clazz">
<id property="id" column="id"/>
<result property="code" column="code"/>
<result property="name" column="name"/>
</association>
</resultMap> </mapper>

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">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
<!-- 指定 MyBatis 所用日志的具体实现 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
<!-- 要使延迟加载生效必须配置下面两个属性 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<environments default="mysql">
<!-- 环境配置,即连接的数据库。 -->
<environment id="mysql">
<!-- 指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
<transactionManager type="JDBC"/>
<!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.47.151:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<mapper resource="mapper/ClazzMapper.xml"/>
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>

ClazzMapp.java

public interface ClazzMapper {

	// 根据id查询班级信息
Clazz selectClazzById(Integer id); }

StudentMapper.java

public interface StudentMapper {

	// 根据id查询学生信息
Student selectStudentById(Integer id); }

测试代码

OneToManyTest.java

public class OneToManyTest {

	public static void main(String[] args) throws Exception {
// 读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 初始化mybatis,创建SqlSessionFactory类的实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// 创建Session实例
SqlSession session = sqlSessionFactory.openSession(); OneToManyTest t = new OneToManyTest(); t.testSelectClazzById(session);
// t.testSelectStudentById(session); // 提交事务
session.commit();
// 关闭Session
session.close();
} // 测试一对多,查询班级Clazz(一)的时候级联查询学生Student(多)
public void testSelectClazzById(SqlSession session){
// 获得ClazzMapper接口的代理对象
ClazzMapper cm = session.getMapper(ClazzMapper.class);
// 调用selectClazzById方法
Clazz clazz = cm.selectClazzById(1);
System.out.println(clazz);
// 查看查询到的clazz对象信息
System.out.println(clazz.getId() + " "+ clazz.getCode() + " "+clazz.getName());
// 查看clazz对象关联的学生信息
List<Student> students = clazz.getStudents();
for(Student stu : students){
System.out.println(stu);
}
} // 测试多对一,查询学生Student(多)的时候级联查询 班级Clazz(一)
public void testSelectStudentById(SqlSession session){
// 获得StudentMapper接口的代理对象
StudentMapper sm = session.getMapper(StudentMapper.class);
// 调用selectStudentById方法
Student stu = sm.selectStudentById(1);
// 查看查询到的Student对象信息
System.out.println(stu);
// 查看Student对象关联的班级信息
System.out.println(stu.getClazz());
} }

至此一对多关系关系映射测试完成

mybatis关联映射一对多的更多相关文章

  1. 0050 MyBatis关联映射--一对多关系

    一对多关系更加常见,比如用户和订单,一个用户可以有多个订单 DROP TABLE IF EXISTS customer; /*用户表*/ CREATE TABLE customer( `pk` INT ...

  2. (转)Hibernate关联映射——一对多(多对一)

    http://blog.csdn.net/yerenyuan_pku/article/details/70152173 Hibernate关联映射——一对多(多对一) 我们以客户(Customer)与 ...

  3. MyBatis学习(六)MyBatis关联映射之一对多映射

    数据库中一对多通常使用主外键关联,外键应该在多方,即多方维护关系. 下面举一个简单实例来看看MyBatis怎么处理一对多的关系. 1.创建一个项目,导入所需jar包,导入db.properties配置 ...

  4. MyBatis(五):mybatis关联映射

    Mybatis中表与表之间的关系分为一下4类: 1)一对一 2)一对多 3)多对一 4)多对多 创建数据Demo表 数据库表: 用户表user:记录了购买商品的用户信息. 订单表orders:记录了用 ...

  5. spring boot(9)-mybatis关联映射

    一对多 查询type表的某一条数据,并且要同时查出所有typeid与之配置的user,最终要得到一个以下类型的Type对象 public class Type { String id; String ...

  6. 0049 MyBatis关联映射--一对一关系

    世上的事务总不是孤立存在的,表现在Java类里面,则是类与类之间的关系,比如继承is-a.依赖use-a.关联has-a,反映在数据库中,则是表与表之间的关系,比如外键 关联关系存在着以下几种类型:一 ...

  7. Spring Boot (11) mybatis 关联映射

    一对多 查询category中的某一条数据,同时查询该分类下的所有Product. Category.java public class Category { private Integer id; ...

  8. mybatis关联映射多对多

    项目开发中,多对多关系也是非常常见的关系 在数据库中创建表的脚本 table.sql CREATE TABLE tb_user( id INT PRIMARY KEY AUTO_INCREMENT, ...

  9. Hibernate之关联映射(一对多和多对一映射,多对多映射)

    ~~~接着之前的Hibernate框架接着学习(上篇面试过后发现真的需要学习以下框架了,不然又被忽悠让去培训.)~~~ 1:Hibernate的关联映射,存在一对多和多对一映射,多对多映射: 1.1: ...

随机推荐

  1. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.qingmu.mybaitsplus.mapper.UserMapper' available:

    java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.conte ...

  2. Python并发编程内容回顾

    Python并发编程内容回顾 并发编程小结 目录 • 一.到底什么是线程?什么是进程? • 二.Python多线程情况下: • 三.Python多进程的情况下: • 四.为什么有这把GIL锁? • 五 ...

  3. 用 tomcat 部署 Jenkins

    在tomcat 下面部署 Jenkins 版本 tomcat (7.0.94) +  jdk (7) + jenkins (2.46.3) 前两次没有部署成功,应该是 jdk 版本的问题, 如果不成功 ...

  4. js闭包理解与使用场景

    要理解闭包首先要知道什么是函数的作用域链 因为有函数的作用域链存在,所以函数无论在哪里调用,函数都可以使用函数外部作用域的变量. 当一个函数被调用时,会创建一个执行环境及相应的作用域链.然后使用arg ...

  5. spark基础知识二

    主要围绕spark的底层核心抽象RDD进行理解.主要包括以下几个方面 RDD弹性分布式数据集的概念 RDD弹性分布式数据集的五大属性 RDD弹性分布式数据集的算子操作分类 RDD弹性分布式数据集的算子 ...

  6. nginx 动静分离之 tomcat

    配置文件示例 server { listen ; server_name www.xxx.com; location ~* "\.(jpg|png|jepg|js|css|xml|bmp|s ...

  7. vb.net 读取 excel

    Dim myConn AsNew ADODB.Connection myConn.CursorLocation = ADODB.CursorLocationEnum.adUseClient '   用 ...

  8. 分布式事务解决方案(二)消息系统避免分布式事务 & MQ事务消息 & Sagas 事务模型

    参考文档: 如何用消息系统避免分布式事务:http://blog.jobbole.com/89140/ https://www.cnblogs.com/savorboard/p/distributed ...

  9. 2018-2019-2 网络对抗技术 20165318 Exp7 网络欺诈防范

    2018-2019-2 网络对抗技术 20165318 Exp7 网络欺诈防范 原理与实践说明 实践目标 实践内容概述 基础问题回答 实践过程记录 简单应用SET工具建立冒名网站 ettercap D ...

  10. eclipse&myeclipse 生成jar包后,spring无法扫描到bean定义

    问题:eclipse&myeclipse 生成jar包后,spring无法扫描到bean定义 在使用getbean或者扫包时注入bean失败,但在IDE里是可以正常运行的? 原因:导出jar未 ...