mybatis级联
mybatis中有时候表不能都分成单表进行查询,表之间会有联系,这时候需要将表进行级联
下面讲一下如何将mybatis中 的表进行级联。映射表关系如下
1:创建数据表
DROP TABLE IF EXISTS t_female_health_form;
DROP TABLE IF EXISTS t_male_health_form;
DROP TABLE IF EXISTS t_task;
DROP TABLE IF EXISTS t_work_card;
DROP TABLE IF EXISTS t_employee_task;
DROP TABLE IF EXISTS t_employee; CREATE TABLE t_employee(
id int(12) not null auto_increment,
real_name varchar(60) not null,
sex int(12) not null comment '1 - 男 0 - 女',
birthday Date not null,
mobile varchar(40) not null,
position varchar(20) not null,
note varchar(234),
primary key (id)
); create table t_employee_task(
id int(12) not null,
emp_id int(12) not null,
task_id int(12) not null,
task_name varchar(60) not null,
note varchar(256),
primary key (id)
); create table t_female_health_form(
id int(12) not null auto_increment,
emp_id int(12) not null,
heart varchar(64) not null,
liver varchar(64) not null,
spleen varchar(64) not null,
lung varchar(64) not null,
kidney varchar(64) not null,
uterus varchar(64) not null,
note varchar(64),
primary key (id)
); create table t_male_health_form(
id int(12) not null auto_increment,
emp_id int(12) not null,
heart varchar(64) not null,
liver varchar(64) not null,
spleen varchar(64) not null,
lung varchar(64) not null,
kidney varchar(64) not null,
uterus varchar(64) not null,
note varchar(64),
primary key (id)
); create table t_task(
id int(12) not null,
title varchar(60) not null,
context varchar(256) not null,
note varchar(256),
primary key(id)
); create table t_work_card(
id int(12) not null auto_increment,
emp_id int(12) not null,
real_name varchar(64) not null,
department varchar(64) not null,
mobile varchar(64) not null,
position varchar(64) not null,
note varchar(256),
primary key (id)
); alter table t_employee_task add constraint fk_reference_4 foreign key (task_id) references t_employee (id) on delete restrict on update restrict; alter table t_employee_task add constraint fk_reference_8 foreign key (task_id) references t_task (id) on delete restrict on update restrict; alter table t_female_health_form add constraint fk_reference_5 foreign key (emp_id) references t_employee (id) on delete restrict on update restrict; alter table t_male_health_form add constraint fk_reference_6 foreign key (emp_id) references t_employee (id) on delete restrict on update restrict; alter table t_work_card add constraint fk_reference_7 foreign key (emp_id) references t_employee (id) on delete restrict on update restrict;
2:创建对应于数据表的pojo
package com.liyafei.pojo; import java.util.Date;
import java.util.List; /**
* 雇员父类
* @author admin
*
*/
public class Employee { private Long id;
private String realName;
private SexEnum sex=null;
private Date birthday;
private String mobile;
private String email;
private String position;
private String note;
//工牌按一对一级联
private WorkCard workCard; public WorkCard getWorkCard() {
return workCard;
}
public void setWorkCard(WorkCard workCard) {
this.workCard = workCard;
}
public List<EmployeeTask> getEmployeeTaskList() {
return employeeTaskList;
}
public void setEmployeeTaskList(List<EmployeeTask> employeeTaskList) {
this.employeeTaskList = employeeTaskList;
}
//雇员任务,一对多级联
private List<EmployeeTask> employeeTaskList=null;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public SexEnum getSex() {
return sex;
}
public void setSex(SexEnum sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
package com.liyafei.pojo; public class EmployeeTask { private Long id;
private Long empId;
private Task task=null;
private String taskName;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
package com.liyafei.pojo; public class FemaleEmployee extends Employee{ private FemaleHealthForm femaleHealthForm=null; public FemaleHealthForm getFemaleHealthForm() {
return femaleHealthForm;
} public void setFemaleHealthForm(FemaleHealthForm femaleHealthForm) {
this.femaleHealthForm = femaleHealthForm;
} }
package com.liyafei.pojo; public class FemaleHealthForm extends HealthForm{ private String uterus; public String getUterus() {
return uterus;
} public void setUterus(String uterus) {
this.uterus = uterus;
}
}
package com.liyafei.pojo; /**
* 体检表父类
* @author admin
*
*/
public class HealthForm { private Long id;
private Long empId;
private String heart;
private String liver;
private String spleen;
private String lung;
private String kidney;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getHeart() {
return heart;
}
public void setHeart(String heart) {
this.heart = heart;
}
public String getLiver() {
return liver;
}
public void setLiver(String liver) {
this.liver = liver;
}
public String getSpleen() {
return spleen;
}
public void setSpleen(String spleen) {
this.spleen = spleen;
}
public String getLung() {
return lung;
}
public void setLung(String lung) {
this.lung = lung;
}
public String getKidney() {
return kidney;
}
public void setKidney(String kidney) {
this.kidney = kidney;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
package com.liyafei.pojo; public class MaleEmployee extends Employee{
private MaleHealthForm maleHealthForm=null; public MaleHealthForm getMaleHealthForm() {
return maleHealthForm;
} public void setMaleHealthForm(MaleHealthForm maleHealthForm) {
this.maleHealthForm = maleHealthForm;
} }
package com.liyafei.pojo; /**
* 女性体检表
* @author admin
*
*/
public class MaleHealthForm extends HealthForm{ private String prostate; public String getProstate() {
return prostate;
} public void setProstate(String prostate) {
this.prostate = prostate;
}
}
package com.liyafei.pojo; public class Task { private Long id;
private String title;
private String context;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
package com.liyafei.pojo; public class WorkCard { private Long id;
private Long empId;
private String realName;
private String department;
private String mobile;
private String position;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
3:Employee中有枚举类SexEnum进行区分性别
创建SexEnum枚举类并创建类型处理器,将数据库中的int类型转换成SexEnum
package com.liyafei.pojo; public enum SexEnum { MALE(1,"男"),
FEMALE(0,"女");
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private SexEnum(int id,String name) {
// TODO Auto-generated constructor stub
this.id=id;
this.name=name;
}
public static SexEnum getSexById(int id){
for(SexEnum sex:SexEnum.values()){
if(sex.getId()==id)
return sex;
}
return null;
}
} package com.liyafei.typeHandler; import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler; import com.liyafei.pojo.SexEnum; /**
* 自定义typeHandler
* 把数据库中的数据类型int转化为SexEnum
* 1=FEMALE
* 0=MALE
* @author admin
*
*/
public class SexTypeHandler implements TypeHandler<SexEnum> { public SexEnum getResult(ResultSet rs, String columnName) throws SQLException {
// TODO Auto-generated method stub
int id=rs.getInt(columnName);
return SexEnum.getSexById(id);
} public SexEnum getResult(ResultSet rs, int columnIndex) throws SQLException {
// TODO Auto-generated method stub
int id=rs.getInt(columnIndex);
return SexEnum.getSexById(id);
} public SexEnum getResult(CallableStatement cs, int columnIndex) throws SQLException {
// TODO Auto-generated method stub
int id=cs.getInt(columnIndex);
return SexEnum.getSexById(id);
} public void setParameter(PreparedStatement ps, int i, SexEnum parameter, JdbcType arg3) throws SQLException {
// TODO Auto-generated method stub
ps.setInt(i, parameter.getId());
} }
4:创建基础配置文件和mapper文件
<?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>
<mappers>
<mapper resource="mapper/TaskMapper.xml"/>
<mapper resource="mapper/WorkCardMapper.xml"/>
<mapper resource="mapper/EmployeeTaskMapper.xml"/>
<mapper resource="mapper/MaleHealthFormMapper.xml"/>
<mapper resource="mapper/femaleHealthFormMapper.xml"/>
<mapper resource="mapper/EmployeeMapper.xml"/>
</mappers> </configuration> <?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.liyafei.mapper.EmployeeMapper">
<resultMap type="com.liyafei.pojo.Employee" id="employee">
<id column="id" property="id"/>
<result column="real_name" property="realName"/> <!-- 使用自定义typeHandler,将数据库中的(int类型)sex转换为pojo中的(SexEnum类型)sex属性 -->
<result column="sex" property="sex" typeHandler="com.liyafei.typeHandler.SexTypeHandler"/>
<result column="birthday" property="birthday"/>
<result column="mobile" property="mobile"/>
<result column="email" property="email"/>
<result column="position" property="position"/>
<result column="note" property="note"/>
<!-- 一对一级联 -->
<association property="workCard" column="id" select="com.liyafei.mapper.WorkCardMapper.getWorkCardByEmpId"></association>
<!-- 一对多级联 -->
<collection property="employeeTaskList" column="id" select="com.liyafei.mapper.EmployeeTaskMapper.getEmployeeTaskByEmpid"></collection>
<!-- 鉴别器 -->
<discriminator javaType="long" column="sex">
<case value="1" resultMap="maleHealthFormMapper"></case>
<case value="2" resultMap="femaleHealthFormMapper"></case>
</discriminator>
</resultMap> <!-- 这个结果集继承自employee结果集 -->
<resultMap type="com.liyafei.pojo.FemaleEmployee" id="femaleHealthFormMapper" extends="employee">
<association property="femaleHealthForm" column="id" select="com.liyafei.mapper.FemaleHealthFormMapper.getFemaleHealthForm"></association> </resultMap>
<!-- 这个结果集继承自employee结果集 -->
<resultMap type="com.liyafei.pojo.MaleEmployee" id="maleHealthFormMapper" extends="employee">
<association property="femaleHealthForm" column="id" select="com.liyafei.mapper.MaleHealthFormMapper.getMaleHealthForm"></association>
</resultMap> <!-- 开启二级缓存,默认是开启了一级缓存 -->
<cache/>
<!-- 可以在查询语句中做sql和pojo 属性的映射,例如real_name as realName -->
<select id="getEmployee" parameterType="long" resultMap="employee">
select id,real_name as realName,sex,birthday,mobile,email,position,note from t_employee where id=#{id}
</select> </mapper> <?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.liyafei.mapper.EmployeeTaskMapper"> <!-- 映射集 ,id映射集标示符,被人引用,type要映射的pojo-->
<resultMap type="com.liyafei.pojo.EmployeeTask" id="EmployeeTaskMap">
<id column="id" property="id"/> <!--id映射的主键,result映射的属性,column是sql的列名,property是pojo的属性 -->
<result column="emp_id" property="empId"/> <!-- 当sql的列名和pojo的属性不一样时,做自定义映射,也可以做自动映射,一般列名role_name将会映射成属性roleName -->
<result column="task_name" property="taskName"/> <!-- 定义的映射不是别名,在下面用不上 -->
<result column="note" property="note"/>
<!-- 通过employeetask表中的task_id与task表相连,一对一级联使用association -->
<!-- EmployeeTask的属性task和getTask(task_id)返回的结果形成映射,结果是一张表 -->
<association property="task" column="task_id"
select="com.liyafei.mapper.TaskMapper.getTask"></association>
</resultMap> <!-- 使用pojo存储结果集 -->
<!-- resultMap是结果集,使用上面定义的pojo映射取代了返回类型,这个将会返回一个pojo EmployeeTask -->
<select id="getEmployeeTaskByEmpId" resultMap="EmployeeTaskMap">
select id,emp_id,task_name,note from t_employee_task where emp_id=#{empId}
</select> </mapper> <?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.liyafei.mapper.FemaleHealthFormMapper">
<select id="getFemaleHealthForm" parameterType="long" resultType="femaleHealthForm">
select id,heart,liver,spleen,lung,kidney,uterus,note from t_male_health_form where emp_id=#{empId}
</select>
</mapper> <?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.liyafei.mapper.MaleHealthFormMapper">
<sql id="tmaleform">
id,heart,liver,spleen,lung,kidney,prostate,note
</sql>
<select id="getMaleHealthForm" parameterType="long" resultType="maleHealthForm">
select <include refid="tmaleform" /> from t_male_health_form where emp_id=#{empId}
</select>
</mapper> <?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.liyafei.mapper.TaskMapper">
<select id="getTask" parameterType="long" resultType="task">
select * from t_task where id=#{id}
</select>
</mapper> <?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.liyafei.mapper.WorkCardMapper">
<select id="getWorkCardByEmpId" parameterType="long" resultType="workCard">
select * from t_task where emp_id=#{empId}
</select>
</mapper>
5:根据***Mapper.xml创建对应的mapper接口
package com.liyafei.mapper; import com.liyafei.pojo.Employee; public interface EmployeeMapper { public Employee getEmployee(long id);
} package com.liyafei.mapper; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.liyafei.pojo.EmployeeTask; public interface EmployeeTaskMapper {
//@param可以向mapper传递参数
public EmployeeTask getEmployeeTaskByEmpid(@Param("empId")Long empId);
} package com.liyafei.mapper; import com.liyafei.pojo.FemaleHealthForm; public interface FemaleHealthFormMapper { public FemaleHealthForm getFemaleHealthForm(long empId);
} package com.liyafei.mapper; import com.liyafei.pojo.MaleHealthForm; public interface MaleHealthFormMapper { public MaleHealthForm getMaleHealthForm(long empId);
} package com.liyafei.mapper; import com.liyafei.pojo.Task; public interface TaskMapper { public Task getTask(Long id);
} package com.liyafei.mapper; import com.liyafei.pojo.WorkCard; public interface WorkCardMapper { public WorkCard getWorkCardByEmpId(long empId);
}
6:mybatis的配置文件application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo
username: root
password: 1367356 mybatis:
mapper-locations: classpath:mapper/*.xml
config-location: classpath:mybatis-config.xml
type-aliases-package: com.liyafei.dao.pojo
7:使用spring boot创建工程的pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liyafei</groupId>
<artifactId>mybatisCascade</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<webVersion>3.1</webVersion>
<mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies> <!-- Spring-Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- Add typical dependencies for a web application -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency> <!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency> </dependencies>
<build> <!-- 将工程打包成可执行jar文件 -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
ok
mybatis级联的更多相关文章
- (三)mybatis级联的实现
mybatis级联的实现 开篇 级联有三种对应关系: 1.一对一(association):如学号与学生 2.一对多(collection):如角色与用户 3.多对多(discri ...
- Mybatis 级联查询 (一对多 )
后台系统中 涉及到添加试卷 问题 答案的一个模块的.我需要通过试卷 查询出所有的试题,以及试题的答案.这个主要要使用到Mybatis的级联查询. 通过试卷 查询出与该试卷相关的试题(一对多),查询出试 ...
- Mybatis级联:关联、集合和鉴别器的使用
Mybatis中级联有关联(association).集合(collection).鉴别器(discriminator)三种.其中,association对应一对一关系.collection对应一对多 ...
- Mybatis级联,使用JOIN和Associa,以及一些ID覆盖和自动变换。
先说下坑,比如数据库的字段是 DW_ID ,用generator讲mybatis自动转换的时候,会省略下表_变成dwId,所以我们之后自己手动设计的时候也尽量换成dwId: generate的myb ...
- mybatis 级联
级联是一个数据库实体的概念.一对多的级联,一对多的级联,在MyBatis中还有一种被称为鉴别器的级联,它是一种可以选择具体实现类的级联. 级联不是必须的,级联的好处是获取关联数据十分便捷,但是级联过多 ...
- mybatis级联查询,多对一查询问题
在使用Mybatis进行多表级联查询时遇到了一个问题:查询结果只有一项,但正确结果是两项.经测试,SQL语句本身没有问题. 在SQL映射文件(XML)中: <!-- 级联查询数据 --> ...
- Mybaits(9)MyBatis级联-2
一.鉴别器和一对多级联 1.完善体检表,分为男雇员体检和女雇员体检表 (1)持久层dao编写 package com.xhbjava.dao; import com.xhbjava.domain.Ma ...
- mybatis ---- 级联查询 一对多 (集合映射)
关联有嵌套查询和嵌套结果两种方式,本文是按照嵌套结果这种方式来说明的 上一章介绍了多对一的关系,用到了<association></association>,这是一个复杂类型的 ...
- mybatis级联查询
1.定义四个实体.User Role Privilege Resource,他们之间的对于关系为 2.需求:我通过用户名username查找出该用户对应的角色以及角色对应的权限和资源 3 ...
随机推荐
- sg函数的理解
sg,是用来判断博弈问题的输赢的,当sg值为0的时候,就是输,不为0就是赢: 在这之前,我们规定一个对于集合的操作mex,表示最小的不属于该集合的非负整数. 举几个栗子:mex{0,1,2}=3,me ...
- Spark RDD Action 简单用例(二)
foreach(f: T => Unit) 对RDD的所有元素应用f函数进行处理,f无返回值./** * Applies a function f to all elements of this ...
- Maven、SpringBoot框架结构优化
一.创建maven项目,名为test-parent,pom文件如下: ... <artifactId>test-parent</artifactId> <version& ...
- 项目启动报错java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
项目已启动的情况下,MyEclipse异常退出.再次打开后重启项目,项目报错:java.net.SocketException: Unrecognized Windows Sockets error: ...
- 英语专业出身也要走向python
这两年一直徘徊在学习python和放弃python的道路上不断的徘徊,今年终于没有在蹉跎下去,选择了开始新的自我挑战,零基础开始学习python. 作为一名英语专业毕业的文科生,学习编程还是相对有些困 ...
- [No0000161]IDEA初步接触
安装 参考https://blog.csdn.net/qq_35246620/article/details/61191375 安装过程全程默认(路径和快捷方式自定义,不需要下载jre): 启动后全程 ...
- class="no-js"
这是什么意思?看了外网的解释,比较明白了.(When Modernizr runs, it removes the "no-js" class and replaces it wi ...
- iOS开发尺寸记录
https://kapeli.com/cheat_sheets/iOS_Design.docset/Contents/Resources/Documents/index https://help.ap ...
- webpack学习笔记-2-file-loader 和 url-loader
一 .前言 如果我们希望在页面引入图片(包括img的src和background的url).当我们基于webpack进行开发时,引入图片会遇到一些问题. 其中一个就是引用路径的问题.拿backgrou ...
- Java 输入/输出——处理流(BufferedStream、PrintStream、转换流、推回输入流)
关于使用处理流的优势,归纳起来就是两点:(1)对于开发人员来说,使用处理流进行输入/输出操作更简单:(2)使用处理流执行效率更高. 1.BufferedInputStream/BufferedOutp ...