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
本博客为非营利性个人原创,除部分有明确署名的作品外,所刊登的所有作品的著作权均为本人所拥有,本人保留所有法定权利。违者必究