框架应用:Mybatis (三) - 关系映射

你有一张你自己的学生证?(一对一)
你这一年级有多少个学生?(一对多)
班上学生各选了什么课?(多对多)
两张表以上的操作都需要联立多张表,而用SQL语句可以直接联立两张表,用工程语言则需要手动完成这些关系对接.如mybatis需要手动配置表之间的关系,作为结果.
一对一映射
创建student, cards 表
DROP TABLE students1;
DROP TABLE cards1;
CREATE TABLE cards1(
id ) PRIMARY KEY,
num )
);
CREATE TABLE students1(
id ) PRIMARY KEY,
name ),
cid ),
CONSTRAINT cid_fk FOREIGN KEY(cid) references cards1(id)
);
,');
,);
table1.sql
创建Student和Card实体类
package com.harry.entity;
import java.io.Serializable;
public class Card implements Serializable {
private Integer id;
private String num;
private Student student;
public Card() {
super();
}
public Card(Integer id, String num, Student student) {
super();
this.id = id;
this.num = num;
this.student = student;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
@Override
public String toString() {
return "Card [id=" + id + ", num=" + num + ", student=" + student + "]";
}
}
Card.java
package com.harry.entity;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String name;
private Card card;
public Student() {
super();
}
public Student(Integer id, String name, Card card) {
super();
this.id = id;
this.name = name;
this.card = card;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", card=" + card + "]";
}
}
Student.java
创建StudentMapper.xml和CardMapper.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="cardNamespace">
<resultMap type="com.harry.entity.Card1" id="cardMap">
<id property="id" column="id" />
<result property="num" column="num" />
</resultMap>
</mapper>
CardMapper.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="studentNamespace">
<!-- 设置返回多个结果,封装于map中 -->
<resultMap type="com.harry.entity.Student1" id="studentMap">
<id property="id" column="id" />
<result property="name" column="name"/>
<association property="card" resultMap="cardNamespace.cardMap"/>
</resultMap>
<select id="findById" parameterType="int" resultMap="studentMap">
SELECT s.id,s.name,c.id,c.num
FROM students1 s INNER JOIN cards1 c
ON s.cid = c.id
AND s.id = #{id}
</select>
</mapper>
StudentMapper.xml
创建StudentCardDao,实现查找一名学生信息时同时获取该学生的学生卡信息
package com.harry.dao;
import org.apache.ibatis.session.SqlSession;
import com.harry.entity.Student;
import com.harry.util.MybatisUtil;
public class StudentCardDao {
public Student findById(Integer id) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
return sqlSession.selectOne("studentNamespace.findById",id);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
}
StudentCardDao.java
实现结果

一个学生对应了一张卡,你可以通过查询一名学生得知该学生的学生证.
一对多映射
执行table2.sql
DROP TABLE students2;
DROP TABLE grades2;
CREATE TABLE grades2(
gid ) PRIMARY KEY,
gname )
);
CREATE TABLE students2(
sid ) PRIMARY KEY,
sname ),
sgid ),
constraINT sgid_fk FOREIGN KEY(sgid) REFERENCES grades2(gid)
);
,'java');
,);
,);
table2.sql
创建两个互相映射的实体类
package com.harry.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 班级(单方)
* @author AdmINTC
*/
public class Grade2 implements Serializable{
private Integer id;
private String name;
private List<Student2> studentList = new ArrayList<Student2>();
public Grade2(){}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student2> getStudentList() {
return studentList;
}
public void setStudentList(List<Student2> studentList) {
this.studentList = studentList;
}
}
Grade2.java
package com.harry.entity;
import java.io.Serializable;
/**
* 学生(多方)
* @author AdmINTC
*/
public class Student2 implements Serializable{
private Integer id;
private String name;
private Grade2 grade;
public Student2(){}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Grade2 getGrade() {
return grade;
}
public void setGrade(Grade2 grade) {
this.grade = grade;
}
}
Student2.java
创建映射文件
<?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="gradeNamespace">
<resultMap type="com.harry.entity.Grade2" id="grade2Map">
<id property="id" column="gid" />
<result property="name" column="gname"/>
<collection property="studentList" resultMap="studentNamespace.student2Map"/>
</resultMap>
<select id="findGrade2ByName" parameterType="string" resultMap="grade2Map">
SELECT g.gid,g.gname,s.sid,s.sname
FROM grades2 g,students2 s
WHERE g.gid = s.sgid
AND s.sname = #{name}
</select>
</mapper>
Grade2Mapper.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="studentNamespace">
<resultMap type="com.harry.entity.Student2" id="student2Map">
<id property="id" column="sid" />
<result property="name" column="sname"/>
<association property="grade" resultMap="gradeNamespace.grade2Map"/>
</resultMap>
<select id="findAllByName" parameterType="string" resultMap="student2Map">
SELECT s.sid,s.sname,g.gid,g.gname
FROM grades2 g,students2 s
WHERE g.gid = s.sgid
AND g.gname = #{name}
</select>
</mapper>
Student2Mapper.xml
创建dao文件
package com.harry.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.harry.entity.Grade2;
import com.harry.entity.Student2;
import com.harry.util.MybatisUtil;
public class GradeStudentDao {
/**
* 查询java班级有哪些【学生】
*/
public List<Student2> findAllByName(String name) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
return sqlSession.selectList("studentNamespace.findAllByName",name);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
/**
* 查询哈哈属于哪个【班级】
*/
public Grade2 findGradeByName(String name) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
return sqlSession.selectOne("gradeNamespace.findGrade2ByName",name);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
}
GradeStudentDao.java
创建测试方法
@Test
public void Test1vn() throws Exception{
GradeStudentDao dao = new GradeStudentDao();
List<Student2> studentList = dao.findAllByName("java");
for(Student2 s : studentList){
System.out.println(s.getId()+":"+s.getName()+":"+s.getGrade().getId()+":"+s.getGrade().getName());
}
Grade2 grade = dao.findGradeByName("Freddie Flowers");
System.out.println(grade.getId()+":"+grade.getName());
}
MybatisTest.java
结果

一个年级对应多名学生,你查询这些学生的年级时可以得到同一年级,又或者查询该年级时获取多个学生的名单.
多对多映射
执行table3.sql
DROP TABLE middles3;
DROP TABLE students3;
DROP TABLE courses3;
CREATE TABLE students3(
sid ) PRIMARY KEY,
sname )
);
CREATE TABLE courses3(
cid ) PRIMARY KEY,
cname )
);
CREATE TABLE middles3(
sid ),
cid ),
PRIMARY KEY(sid,cid)
);
,'Janie Ferrell');
,'Audrey Lloyd');
,'java');
,'net');
,);
,);
,);
,);
SELECT * from students3;
SELECT * from courses3;
SELECT * from middles3;
table3.sql
创建映射文件
<?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="courseNamespace">
<resultMap type="com.harry.entity.Course3" id="course3Map">
<id property="id" column="cid" />
<result property="name" column="cname"/>
</resultMap>
<select id="findCourseByName" parameterType="string" resultMap="course3Map">
SELECT c.cid,c.cname
FROM students3 s,middles3 m,courses3 c
WHERE s.sid = m.sid
AND m.cid = c.cid
AND s.sname = #{name}
</select>
</mapper>
Course3Mapper.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="studentNamespace">
<resultMap type="com.harry.entity.Student3" id="student3Map">
<id property="id" column="sid" />
<result property="name" column="sname"/>
</resultMap>
<select id="findStudentByName" parameterType="string" resultMap="student3Map">
SELECT s.sid,s.sname
FROM students3 s,middles3 m,courses3 c
WHERE s.sid = m.sid
AND m.cid = c.cid
AND c.cname = #{name}
</select>
</mapper>
Student3Mapper.xml
创建dao
package com.harry.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.harry.entity.Course3;
import com.harry.entity.Student3;
import com.harry.util.MybatisUtil;
public class CourseStudentDao {
/**
* 查询哈哈选学的【课程】
*/
public List<Course3> findCourseByName(String name) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
return sqlSession.selectList("courseNamespace.findCourseByName",name);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
/**
* 查询java课程有哪些【学生】
*/
public List<Student3> findStudentByName(String name) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
return sqlSession.selectList("studentNamespace.findStudentByName",name);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
}
CourseStudentDao.java
创建测试方法
@Test
public void Testnvm() throws Exception{
CourseStudentDao dao = new CourseStudentDao();
List<Course3> courseList = dao.findCourseByName("Janie Ferrell");
for(Course3 c : courseList){
System.out.println(c.getId()+":"+c.getName());
}
List<Student3> studentList = dao.findStudentByName("java");
for(Student3 s : studentList){
System.out.println(s.getId()+":"+s.getName());
}
}
MybatisTest.java
结果


多门课对应多个学生,不同于一对一和一对多关系,表示多对多关系时常常需要一张中间表来保存另外两张特定的表项ID.你查询一门课可以返回学生名单,同时你查询某一学生时可以返回选课名单.
附源码
框架应用:Mybatis (三) - 关系映射的更多相关文章
- MyBatis加强(1)~myBatis对象关系映射(多对一关系、一对多关系)、延迟/懒加载
一.myBatis对象关系映射(多对一关系.一对多关系) 1.多对一关系: ---例子:多个员工同属于一个部门. (1)myBatis发送 额外SQL: ■ 案例:员工表通过 dept_id 关联 部 ...
- 【mybatis xml】数据层框架应用--Mybatis 基于XML映射文件实现数据的CRUD
使用MyBatis框架进行持久层开发 MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架. MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索. MyBa ...
- Mybatis对象关系映射 one2one,one2many,many2many
MyBatis中的高级映射一般要借助select元素中的resultMap属性进行实现,通过此属性配置实现一对一,一对多等关系映射的实现 一对一映射:association 一对多映射:collect ...
- 第9章 MyBatis的关系映射
在实际开发中,对数据库的操作通常涉及多张表,涉及了对象和对象之间的关联关系.针对多表之间的操作,MyBatis提供了关联映射,通过关联映射就可以很好的处理对象与对象之间的关联关系 9.1 关联关系概述 ...
- mybatis的关系映射
一.多对一的映射关系 举例:根据员工编号查询员工所在部门的部门信息 第一步,需要在多的一方也就是员工实体类中持有一的一方部门实体类的引用 第二步,在dao接口中声明方法 第三步,在mapper中实现该 ...
- ssh架构之hibernate(三)关系映射
1.单向多对一 1.映射文件配置 2.model: 测试 1.查询测试 执行顺序,先查询多方,在查询一方,一方采用延迟加载 注意:如果不使用一方的数据,就关闭session,报错,同延迟加载中的报错类 ...
- mybatis 对象关系映射例子
入门 http://legend2011.blog.51cto.com/3018495/908956 增删改 http://legend2011.blog.51cto.com/3018495/9130 ...
- [刘阳Java]_MyBatis_实体关系映射_第8讲
MyBatis既然是一个ORM框架,则它也有像Hibernate那样的一对多,多对多,多对一的实体关系映射功能.下面我们就来介绍一下如何使用MyBatis的实体关系映射 1.MyBatis实体关系映射 ...
- 【mybatis xml】数据层框架应用--Mybatis(三)关系映射之一对一关系映射
实际的开发中,对数据库的操作常常会涉及到多张表,这在面向对象中就涉及到了对象与对象之间的关联关系. 针对多表之间的操作,MyBatis提供了关联映射,通过关联映射就可以很好的处理对象与对象之间的关联关 ...
随机推荐
- MySQL 参数autoReconnect=true 解决8小时连接失效(转)
即使在创建Mysql时url中加入了autoReconnect=true参数,一但这个连接两次访问数据库的时间超出了服务器端wait_timeout的时间限制,还是会CommunicationsExc ...
- fodera20安装后的配置
最近安装了Fedora 20 64bit,以下是一些优化配置,使之更适合国人使用. 1,安装gnome-tweak-tool设置工具 Fedora 19自带的系统设置工具十分简单,一些重要的地方都不能 ...
- centos下安装jenkins
To use this repository, run the following command: sudo wget -O /etc/yum.repos.d/jenkins.repo https: ...
- vue-cli脚手架npm相关文件解读(4)utils.js
系列文章传送门: 1.build/webpack.base.conf.js 2.build/webpack.prod.conf.js 3.build/webpack.dev.conf.js 4.bui ...
- 监听 window.open 打开的窗口关闭并回调
第三方的登录的解决方案通常有两种方式,一是打开一个新的标签页,然后登录回调回来: 二是通过父窗口打开一个子窗体去第三方登录,登陆成功时关掉子窗体回到父窗口. 问题来了 我的父窗体怎么样才知道子窗体被关 ...
- 斜率DP hdu 3507
Problem Description Zero has an old printer that doesn't work well sometimes. As it is antique, he s ...
- python汉字输出编码问题
python中文输出乱码问题困扰了多少初学者,我在这方面栽了不知道多少跟头.现在我把我碰到的问题和解决的方法写出来与大家分享一下: 1输出乱码 所谓的乱码是指“鎴戞槸涓枃瀛楃涓”这样的内容.为什么 ...
- Servlet总结一
Servlet总结一 HttpServlet 想要实现一个servlet必须继承这个类,其实一个servlet就是一个java文件,但是这个类必须是继承HttpServlet. 生命周期 servle ...
- C# 引用类型之特例string
在C#编程的时候经常会使用字符串(string)类型,它也是引用类型,但是处处都不作为引用的用法来使用,实属特例,下来我一一罗列出来,供自己记忆方便: 1)字符串的直接赋值:本身字符串就是引用类型,应 ...
- 个人作业2——必应词典APP分析
第一部分:调研.评测 1.刚刚打开必应词典的时候,它给我的第一反应就是界面美观,最上面是一个查询框,下面有一些经典的句子.单词以及一些精选的文章,所有的功能都可以一目了然,看一眼就知道要怎么去使用,这 ...