mybatis关联映射一对多
实际项目中也存在很多的一对多的情况,下面看看这个简单的例子
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关联映射一对多的更多相关文章
- 0050 MyBatis关联映射--一对多关系
一对多关系更加常见,比如用户和订单,一个用户可以有多个订单 DROP TABLE IF EXISTS customer; /*用户表*/ CREATE TABLE customer( `pk` INT ...
- (转)Hibernate关联映射——一对多(多对一)
http://blog.csdn.net/yerenyuan_pku/article/details/70152173 Hibernate关联映射——一对多(多对一) 我们以客户(Customer)与 ...
- MyBatis学习(六)MyBatis关联映射之一对多映射
数据库中一对多通常使用主外键关联,外键应该在多方,即多方维护关系. 下面举一个简单实例来看看MyBatis怎么处理一对多的关系. 1.创建一个项目,导入所需jar包,导入db.properties配置 ...
- MyBatis(五):mybatis关联映射
Mybatis中表与表之间的关系分为一下4类: 1)一对一 2)一对多 3)多对一 4)多对多 创建数据Demo表 数据库表: 用户表user:记录了购买商品的用户信息. 订单表orders:记录了用 ...
- spring boot(9)-mybatis关联映射
一对多 查询type表的某一条数据,并且要同时查出所有typeid与之配置的user,最终要得到一个以下类型的Type对象 public class Type { String id; String ...
- 0049 MyBatis关联映射--一对一关系
世上的事务总不是孤立存在的,表现在Java类里面,则是类与类之间的关系,比如继承is-a.依赖use-a.关联has-a,反映在数据库中,则是表与表之间的关系,比如外键 关联关系存在着以下几种类型:一 ...
- Spring Boot (11) mybatis 关联映射
一对多 查询category中的某一条数据,同时查询该分类下的所有Product. Category.java public class Category { private Integer id; ...
- mybatis关联映射多对多
项目开发中,多对多关系也是非常常见的关系 在数据库中创建表的脚本 table.sql CREATE TABLE tb_user( id INT PRIMARY KEY AUTO_INCREMENT, ...
- Hibernate之关联映射(一对多和多对一映射,多对多映射)
~~~接着之前的Hibernate框架接着学习(上篇面试过后发现真的需要学习以下框架了,不然又被忽悠让去培训.)~~~ 1:Hibernate的关联映射,存在一对多和多对一映射,多对多映射: 1.1: ...
随机推荐
- AQS 抽象队列同步器(Abstract Queued Synchronizer) 知识点
AQS的主要使用方式是继承,子类通过继承同步器并实现它的抽象方法来管理同步状态. AQS使用一个int类型的成员变量state来表示同步状态,当state>0时表示已经获取了锁,当state = ...
- css display:inline
- 12 opencv图像合成
#include < stdio.h > #include < opencv2\opencv.hpp > #include < opencv2\stitching.hpp ...
- LeetCode 825. Friends Of Appropriate Ages
原题链接在这里:https://leetcode.com/problems/friends-of-appropriate-ages/ 题目: Some people will make friend ...
- Windows server 2003 粘滞键后门+提权
Windows server 2003中可以建立粘滞键与cmd的连接来绕过已经设置好的安全机制做一些事情,比如新建用户.提权 粘滞键介绍 网上查了一些资料,也没怎么说明白,不如自己试一下,大概意思就是 ...
- 关于System.FormatException异常
什么是FormatException 参数格式无效或复合格式字符串不正确时引发的异常. 继承 Object Exception SystemException FormatException 详细说明 ...
- 编写一个方法去掉数组里面重复的内容 var arr=['abc','abcd','sss','2','d','t','2','ss','f','22','d'];
function noRepeat(arr) { var arr1 = []; for (var i = 0; i < arr.length; i++) { var item = arr[i]; ...
- 请用js写一个函数,实现获取浏览器url中查询字符串中的参数并返回一个数组
<script> console.log(getUrlArr()); function getUrlArr() { var arr = []; var url = "http:/ ...
- Vue实践TS中的一些常见错误解决方案
mixin报错 import { Component, Prop, Vue ,Mixins} from 'vue-property-decorator' import httpminix from ' ...
- luoguP2039 [AHOI2009]跳棋 巧妙的dp
设\(f[i]\)表示在第\(i\)个格子上弄一个棋子的最小代价,前后扫两遍dp后统计答案即可. 代码 #include<bits/stdc++.h> using namespace st ...