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级联的更多相关文章

  1. (三)mybatis级联的实现

    mybatis级联的实现 开篇         级联有三种对应关系: 1.一对一(association):如学号与学生  2.一对多(collection):如角色与用户  3.多对多(discri ...

  2. Mybatis 级联查询 (一对多 )

    后台系统中 涉及到添加试卷 问题 答案的一个模块的.我需要通过试卷 查询出所有的试题,以及试题的答案.这个主要要使用到Mybatis的级联查询. 通过试卷 查询出与该试卷相关的试题(一对多),查询出试 ...

  3. Mybatis级联:关联、集合和鉴别器的使用

    Mybatis中级联有关联(association).集合(collection).鉴别器(discriminator)三种.其中,association对应一对一关系.collection对应一对多 ...

  4. Mybatis级联,使用JOIN和Associa,以及一些ID覆盖和自动变换。

    先说下坑,比如数据库的字段是 DW_ID  ,用generator讲mybatis自动转换的时候,会省略下表_变成dwId,所以我们之后自己手动设计的时候也尽量换成dwId: generate的myb ...

  5. mybatis 级联

    级联是一个数据库实体的概念.一对多的级联,一对多的级联,在MyBatis中还有一种被称为鉴别器的级联,它是一种可以选择具体实现类的级联. 级联不是必须的,级联的好处是获取关联数据十分便捷,但是级联过多 ...

  6. mybatis级联查询,多对一查询问题

    在使用Mybatis进行多表级联查询时遇到了一个问题:查询结果只有一项,但正确结果是两项.经测试,SQL语句本身没有问题. 在SQL映射文件(XML)中: <!-- 级联查询数据 --> ...

  7. Mybaits(9)MyBatis级联-2

    一.鉴别器和一对多级联 1.完善体检表,分为男雇员体检和女雇员体检表 (1)持久层dao编写 package com.xhbjava.dao; import com.xhbjava.domain.Ma ...

  8. mybatis ---- 级联查询 一对多 (集合映射)

    关联有嵌套查询和嵌套结果两种方式,本文是按照嵌套结果这种方式来说明的 上一章介绍了多对一的关系,用到了<association></association>,这是一个复杂类型的 ...

  9. mybatis级联查询

    1.定义四个实体.User   Role    Privilege   Resource,他们之间的对于关系为 2.需求:我通过用户名username查找出该用户对应的角色以及角色对应的权限和资源 3 ...

随机推荐

  1. 【.NetCore学习】ubuntu16.04 搭建.net core mvc api 运行环境

    查看linux内核版本 uname -a 打印结果 python@ubuntu:~$ uname -a Linux ubuntu 4.4.0-31-generic #50-Ubuntu SMP Wed ...

  2. Kubernetes部署SpringCloud(二) 部署ZUUL与服务 非host, 伸缩与负载均衡

    因为服务需要可缩容,所以不能使用host部署. 涉及两个应用,zuul,basic-info-api 验证,在k8s任意一个node 从zuul 访问 basic-info-api 创建一个Sprin ...

  3. rayleighchan实现瑞利多径衰落信

    rayleighchan实现瑞利多径衰落信道 1.命令格式: chan = rayleighchan(ts,fd,tau,pdb) 其中: ts—为输入信号的采样周期, fd—就是Doppler频偏, ...

  4. 如何用JQuery实现单元格 循环变背景色

    要不断循环最好用 setInterval 吧var i = 0;var obj = $("tr td");setInterval(function(){ obj.css(" ...

  5. 微信jssdk上传图片,一张一张的上传 和 一次性传好几张

    //html模板 <div class="zhaopin_3_2"> <div id="bbb"></div> <im ...

  6. db2 backup export

    备份命令: db2 backup db test to /db2data/ 监控备份进度: db2 list utilities show detail <-进度 检测备份文件的有效性: db2 ...

  7. org.hibernate.HibernateException: connnection proxy not usable after transaction completion

    今天yuan男神的程序报了这个错, getHibernateTemplate().saveOrUpdate(obj); getHibernateTemplate().flush(); getHiber ...

  8. python中的日志,logger用法

    python中自带logger模块,实现方法有两种,一般使用第二种,更灵活 方法一: import logging # 通过logging.basicConfig完成 logging.basicCon ...

  9. React组件中的key

    React组件中的key 一.key的作用 react中的key属性,它是一个特殊的属性,它是出现不是给开发者用的(例如你为一个组件设置key之后不能获取组件的这个key props),而是给reac ...

  10. 【视频】dx dy的意思 微分的定义 导数符号的意思

    视频解说 http://www.bilibili.com/video/av8565224/