Mybatis中的3種級聯方式

Mybatis中的級聯

Mybatis的3種級聯

  1. 鑑別器(discriminator): 他是一個根據某些條件決定採用具體實現類的級聯的方案,比如體檢要根據性別區分。
  2. 一對一(association): 比如你的省份證和你就是一種一對一的級聯。
  3. 一對多(collection): 比如班主任和學生就是一種一對多的級聯。

值得注意的是,Mybatis中沒有多對多的級聯,因爲多對多級聯比較複雜。使用困難,而且可以通過兩個一對多級聯進行替換,所以Mybatis不支持多對多級聯。

示例

  • 確定一個僱員級聯模型
    僱員級聯模型

分析僱員級聯模型

1. 該模型是以僱員表爲中心的。
2. 僱員表和工牌表示 “一對一” 的級聯關係。
3. 僱員表和員工任務表示 “ 一對多” 的級聯關係。
4. 員工任務表和任務表是 “一對一” 的級聯關係。
5. 每個員工都會有一個體檢表,它是根據性別的不同,得到不同的關聯表,所以是 “鑑別器” 的級聯關係。
表的設計

在這裏插入圖片描述

SQL語句
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;

/*==============================================================*/
/* Table: t_employee  僱員表                                    */
/*==============================================================*/
CREATE TABLE t_employee
(
   id                   INT(12) NOT NULL AUTO_INCREMENT,
   real_name            VARCHAR(60) NOT NULL,
   sex                  INT(2) NOT NULL COMMENT '1 - 男 0 -女',
   birthday             DATE NOT NULL,
   mobile               VARCHAR(20) NOT NULL,
   email                VARCHAR(60) NOT NULL,
   POSITION             VARCHAR(20) NOT NULL,
   note                 VARCHAR(256),
   PRIMARY KEY (id)
);

/*==============================================================*/
/* Table: t_employee_task  員工任務表                           */
/*==============================================================*/
CREATE TABLE t_employee_task
(
   id                   INT(12) NOT NULL auto_increment,
   emp_id               INT(12) NOT NULL,
   task_id              INT(12) NOT NULL,
   task_name            VARCHAR(60) NOT NULL,
   note                 VARCHAR(256),
   PRIMARY KEY (id)
);

/*==============================================================*/
/* Table: t_female_health_form 女性體檢表                       */
/*==============================================================*/
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(256),
   PRIMARY KEY (id)
);

/*==============================================================*/
/* Table: t_male_health_form  男性體檢表                        */
/*==============================================================*/
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,
   prostate             VARCHAR(64) NOT NULL,
   note                 VARCHAR(256),
   PRIMARY KEY (id)
);

/*==============================================================*/
/* Table: t_task  任務表                                        */
/*==============================================================*/
CREATE TABLE t_task
(
   id                   INT(12) NOT NULL auto_increment,
   title                VARCHAR(60) NOT NULL,
   context              VARCHAR(256) NOT NULL,
   note                 VARCHAR(256),
   PRIMARY KEY (id)
);

/*==============================================================*/
/* Table: t_work_card  工牌表                                   */
/*==============================================================*/
CREATE TABLE t_work_card
(
   id                   INT(12) NOT NULL AUTO_INCREMENT,
   emp_id               INT(12) NOT NULL,
   real_name            VARCHAR(60) NOT NULL,
   department           VARCHAR(20) NOT NULL,
   mobile               VARCHAR(20) NOT NULL,
   POSITION             VARCHAR(30) NOT NULL,
   note                 VARCHAR(256),
   PRIMARY KEY (id)
);

/*==============================================================*/
/* 外鍵約束                                                     */
/*==============================================================*/
ALTER TABLE t_employee_task ADD CONSTRAINT FK_Reference_4 FOREIGN KEY (emp_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;

/*==============================================================*/
/* 插入測試數據                                                 */
/*==============================================================*/
/*僱員表*/
INSERT INTO t_employee(id,real_name,sex,birthday,mobile,email,POSITION,note) 
			 VALUES (DEFAULT,'employee_1',1,'2000-04-23','18773459883','[email protected]','Programmer','小劉');
INSERT INTO t_employee(id,real_name,sex,birthday,mobile,email,POSITION,note) 
			 VALUES (DEFAULT,'employee_2',1,'2000-01-03','18773324883','[email protected]','Programmer','小王');
INSERT INTO t_employee(id,real_name,sex,birthday,mobile,email,POSITION,note) 
			 VALUES (DEFAULT,'employee_3',0,'2000-02-20','18773443555','[email protected]','Programmer','小徐');
INSERT INTO t_employee(id,real_name,sex,birthday,mobile,email,POSITION,note) 
			 VALUES (DEFAULT,'employee_4',0,'2000-04-29','18773464467','[email protected]','Programmer','小陸');
/*男性體檢表*/
INSERT INTO t_male_health_form(id,emp_id,heart,liver,spleen,lung,kidney,prostate,note)
			 VALUES(DEFAULT,1,'normal','normal','normal','normal','normal','normal','***醫院');
INSERT INTO t_male_health_form(id,emp_id,heart,liver,spleen,lung,kidney,prostate,note)
			 VALUES(DEFAULT,2,'normal','normal','normal','normal','normal','normal','***醫院');
/*女性體檢表*/
INSERT INTO t_female_health_form(id,emp_id,heart,liver,spleen,lung,kidney,uterus,note)
			 VALUES(DEFAULT,3,'normal','normal','normal','normal','normal','normal','***醫院');
INSERT INTO t_female_health_form(id,emp_id,heart,liver,spleen,lung,kidney,uterus,note)
			 VALUES(DEFAULT,4,'normal','normal','normal','normal','normal','normal','***醫院');
/*工牌表*/
INSERT INTO t_work_card(id,emp_id,real_name,department,mobile,POSITION,note) 
			 VALUES (DEFAULT,1,'employee_1','Tech-Dept','[email protected]','Programmer','小劉');
INSERT INTO t_work_card(id,emp_id,real_name,department,mobile,POSITION,note) 
			 VALUES (DEFAULT,2,'employee_2','Tech-Dept','[email protected]','Programmer','小王');
INSERT INTO t_work_card(id,emp_id,real_name,department,mobile,POSITION,note) 
			 VALUES (DEFAULT,3,'employee_3','Tech-Dept','[email protected]','Programmer','小徐');
INSERT INTO t_work_card(id,emp_id,real_name,department,mobile,POSITION,note) 
			 VALUES (DEFAULT,4,'employee_4','Tech-Dept','[email protected]','Programmer','小陸');
/*任務表*/
INSERT INTO t_task(id,title,context,note)
			 VALUE(DEFAULT,'前端','HTML+CSS+JS+JQuery+Bootstrap+Ajax','前端開發');
INSERT INTO t_task(id,title,context,note)
			 VALUE(DEFAULT,'後端','Spring+SpringMVC+Mybatis+Redis','後端開發');
/*員工任務表*/
INSERT INTO t_employee_task(id,emp_id,task_id,task_name,note)
			 VALUES(DEFAULT,1,2,'後端開發','後端');
INSERT INTO t_employee_task(id,emp_id,task_id,task_name,note)
			 VALUES(DEFAULT,2,2,'後端開發','後端');
INSERT INTO t_employee_task(id,emp_id,task_id,task_name,note)
			 VALUES(DEFAULT,3,1,'前端開發','前端');
INSERT INTO t_employee_task(id,emp_id,task_id,task_name,note)
			 VALUES(DEFAULT,4,1,'前端開發','前端');

示例項目主體結構

項目結構

示例代碼

建立POJO

建立POJO之前先建立一個性別枚舉類和一個自定義TypeHandler類
1. SexEnum.java

package com.ssm.enumeration;

/**
 * 性別枚舉
 */
public enum SexEnum {
    MALE(1,"男"),
    FEMALE(0,"女");

    private int id;
    private String name;

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    SexEnum(int id, String name) {
        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;
    }
}

  1. SexTypeHandler.java
package com.ssm.typeHandler;

import com.ssm.enumeration.SexEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SexTypeHandler extends BaseTypeHandler<SexEnum> {
    @Override
    public SexEnum getNullableResult(ResultSet rs, String name) throws SQLException {
        int sex = rs.getInt(name);
        return SexEnum.getSexById(sex);
    }

    @Override
    public SexEnum getNullableResult(ResultSet rs, int index) throws SQLException {
        int sex = rs.getInt(index);
        return SexEnum.getSexById(sex);
    }

    @Override
    public SexEnum getNullableResult(CallableStatement cs, int index) throws SQLException {
        int sex = cs.getInt(index);
        return SexEnum.getSexById(sex);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int index, SexEnum sex, JdbcType jdbcType) throws SQLException {
        ps.setInt(index, sex.getId());
    }
}

  1. 主要實體類
    HealthFoem.java
package com.ssm.pojo;

/**
 * 體檢實體類
 */
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;
	}

	@Override
	public String toString() {
		return "HealthForm{" +
				"id=" + id +
				", empId=" + empId +
				", heart='" + heart + '\'' +
				", liver='" + liver + '\'' +
				", spleen='" + spleen + '\'' +
				", lung='" + lung + '\'' +
				", kidney='" + kidney + '\'' +
				", note='" + note + '\'' +
				'}';
	}
}

MaleHealthForm.java
package com.ssm.pojo;

/**
 * 男性體檢實體類
 */
public class MaleHealthForm extends HealthForm {
	
	private String prostate;

	public String getProstate() {
		return prostate;
	}

	public void setProstate(String prostate) {
		this.prostate = prostate;
	}
}

FemaleHealthForm.java
package com.ssm.pojo;

/**
 * 女性體檢實體類
 */
public class FemaleHealthForm extends HealthForm {

	private String uterus;

	public String getUterus() {
		return uterus;
	}

	public void setUterus(String uterus) {
		this.uterus = uterus;
	}
}

WorkCard.java
package com.ssm.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;
	}

	@Override
	public String toString() {
		return "WorkCard{" +
				"id=" + id +
				", empId=" + empId +
				", realName='" + realName + '\'' +
				", department='" + department + '\'' +
				", mobile='" + mobile + '\'' +
				", position='" + position + '\'' +
				", note='" + note + '\'' +
				'}';
	}
}

Task.java
package com.ssm.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;
	}

	@Override
	public String toString() {
		return "Task{" +
				"id=" + id +
				", title='" + title + '\'' +
				", context='" + context + '\'' +
				", note='" + note + '\'' +
				'}';
	}
}

EmployeeTask.java
package com.ssm.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;
	}

	@Override
	public String toString() {
		return "EmployeeTask{" +
				"id=" + id +
				", empId=" + empId +
				", task=" + task +
				", taskName='" + taskName + '\'' +
				", note='" + note + '\'' +
				'}';
	}
}

Employee.java
package com.ssm.pojo;

import java.util.Date;
import java.util.List;

import com.ssm.enumeration.SexEnum;

/**
 * 僱員實體類
 */
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;
	//僱員任務,一對多級聯
	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;
	}
	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;
	}

	@Override
	public String toString() {
		return "Employee{" +
				"id=" + id +
				", realName='" + realName + '\'' +
				", sex=" + sex +
				", birthday=" + birthday +
				", mobile='" + mobile + '\'' +
				", email='" + email + '\'' +
				", position='" + position + '\'' +
				", note='" + note + '\'' +
				", workCard=" + workCard +
				", employeeTaskList=" + employeeTaskList +
				'}';
	}
}

MaleEmployee.java
package com.ssm.pojo;

/**
 * 男僱員實體類
 */
public class MaleEmployee extends Employee {

	private MaleHealthForm maleHealthForm = null;

	public MaleHealthForm getMaleHealthForm() {
		return maleHealthForm;
	}

	public void setMaleHealthForm(MaleHealthForm maleHealthForm) {
		this.maleHealthForm = maleHealthForm;
	}

}

FemaleEmployee.java
package com.ssm.pojo;

/**
 * 女僱員實體類
 */
public class FemaleEmployee extends Employee {

	private FemaleHealthForm femaleHealthForm = null;

	public FemaleHealthForm getFemaleHealthForm() {
		return femaleHealthForm;
	}

	public void setFemaleHealthForm(FemaleHealthForm femaleHealthForm) {
		this.femaleHealthForm = femaleHealthForm;
	}

}

配置映射文件Mapper

* 數據庫文件和日誌文件
	jdbc.properties
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/employee
database.username=root
database.password=123456
		log4j.properties
log4j.rootLogger=DEBUG , stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
		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">
<configuration>
    <properties resource="jdbc.properties" />

    <typeAliases>
        <package name="com.ssm.pojo"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${database.driver}"/>
                <property name="url" value="${database.url}"/>
                <property name="username" value="${database.username}"/>
                <property name="password" value="${database.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.ssm.mapper"/>
    </mappers>
</configuration>
  • 實體類映射文件和接口
    TaskMapper.java
package com.ssm.mapper;

import com.ssm.pojo.Task;

import java.util.List;

public interface TaskMapper {
    public Task selTask(Long id);
}

	TaskMapper.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="com.ssm.mapper.TaskMapper">
    <select id="selTask" parameterType="long" resultType="task">
        select id,title,context,note
        from t_task
        where id = #{id}
    </select>
</mapper>
	WorkCardMapper.java
package com.ssm.mapper;

import com.ssm.pojo.WorkCard;

import java.util.List;

public interface WorkCardMapper {
    public WorkCard selWorkCardByEmpId(Long empid);
}

	WorkCardMapper.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="com.ssm.mapper.WorkCardMapper">
    <select id="selWorkCardByEmpId" parameterType="long" resultType="workCard">
        select id,emp_id as empid,real_name as realName,department,mobile,position,note
        from t_work_card
        where emp_id = #{empid}
    </select>
</mapper>
	EmployeeTaskMapper.java
package com.ssm.mapper;

import com.ssm.pojo.EmployeeTask;

import java.util.List;

public interface EmployeeTaskMapper {
    public EmployeeTask selEmployeeTaskByEmpId(Long empId);
}

	EmployeeTaskMapper.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="com.ssm.mapper.EmployeeTaskMapper">
    <resultMap id="EmployeeTaskMap" type="com.ssm.pojo.EmployeeTask">
        <id property="empId" column="emp_id"></id>
        <result property="taskName" column="task_name"></result>
        <result property="note" column="note"></result>
        <!--僱員任務表一對一級聯-->
        <association property="task" column="task_id"
                     select="com.ssm.mapper.TaskMapper.selTask"/>
    </resultMap>
    <select id="selEmployeeTaskByEmpId" parameterType="long" resultMap="EmployeeTaskMap">
        select id,emp_id,task_name,note,task_id
        from t_employee_task
        where emp_id = #{empId}
    </select>
</mapper>
	MaleHealthFormMapper.java
package com.ssm.mapper;

import com.ssm.pojo.MaleHealthForm;

import java.util.List;

public interface MaleHealthFormMapper {
    public MaleHealthForm selMaleHealthForm(Long id);
}

	MaleHealthFormMapper.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="com.ssm.mapper.MaleHealthFormMapper">
    <select id="selMaleHealthForm" parameterType="long" resultType="maleHealthForm">
        select id,emp_id as empId,heart,liver,spleen,lung,kidney,prostate,note
        from t_male_health_form
        where emp_id = #{id}
    </select>
</mapper>
	FemaleHealthFormMapper.java
package com.ssm.mapper;

import com.ssm.pojo.FemaleHealthForm;


public interface FemaleHealthFormMapper {
    public FemaleHealthForm selFemaleHealthForm(Long id);
}

	FemaleHealthFormMapper.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="com.ssm.mapper.FemaleHealthFormMapper">
    <select id="selFemaleHealthForm" parameterType="long" resultType="femaleHealthForm">
        select id,emp_id as empId,heart,liver,spleen,lung,kidney,uterus,note
        from t_female_health_form
        where emp_id = #{id}
    </select>
</mapper>
	EmployeeMapper.java
package com.ssm.mapper;

import com.ssm.pojo.Employee;


public interface EmployeeMapper {
    public Employee selEmployee(Long id);
}

	EmployeeMapper.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="com.ssm.mapper.EmployeeMapper">
    <resultMap id="employee" type="com.ssm.pojo.Employee">
        <id property="id" column="id"/>
        <result property="realName" column="real_name"/>
        <result property="sex" column="sex"
                typeHandler="com.ssm.typeHandler.SexTypeHandler"/>
        <result property="birthday" column="birthday"/>
        <result property="mobile" column="mobile"/>
        <result property="email" column="email"/>
        <result property="position" column="position"/>
        <result property="note" column="note"/>
        <!--工牌表一對一級聯-->
        <association property="workCard" column="id"
                     select="com.ssm.mapper.WorkCardMapper.selWorkCardByEmpId"/>
        <!--僱員任務,一對多級聯-->
        <collection property="employeeTaskList" column="id"
                    select="com.ssm.mapper.EmployeeTaskMapper.selEmployeeTaskByEmpId"/>
        <!--鑑別器-->
        <discriminator javaType="long" column="sex">
            <case value="1" resultMap="maleHealthFormMapper"/>
            <case value="0" resultMap="femaleHealthFormMapper"/>
        </discriminator>
    </resultMap>

    <resultMap id="maleHealthFormMapper" type="com.ssm.pojo.MaleEmployee" extends="employee">
        <association property="maleHealthForm" column="id"
                     select="com.ssm.mapper.MaleHealthFormMapper.selMaleHealthForm"/>
    </resultMap>

    <resultMap id="femaleHealthFormMapper" type="com.ssm.pojo.FemaleEmployee" extends="employee">
        <association property="femaleHealthForm" column="id"
                     select="com.ssm.mapper.FemaleHealthFormMapper.selFemaleHealthForm"/>
    </resultMap>
    <select id="selEmployee" parameterType="long" resultMap="employee">
        select id, real_name as realName, sex, birthday, mobile, email, position,note
        from t_employee
        where id = #{id}
    </select>
</mapper>

測試類

EmployeeTest.java
package com.ssm.test;

import com.ssm.mapper.EmployeeMapper;
import com.ssm.mapper.FemaleHealthFormMapper;
import com.ssm.mapper.MaleHealthFormMapper;
import com.ssm.pojo.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.InputStream;

public class EmployeeTest {
    public static void main(String[] args) {
        selEmployee();
    }

    public static void selEmployee(){
        SqlSession session = null;
        Logger logger = Logger.getLogger(EmployeeTask.class);
        try{
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            session = factory.openSession();
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = employeeMapper.selEmployee(3L);
            System.out.println("員工基本信息:"+employee.toString());

            if ((employee.getSex().toString()).equals("MALE")){
                MaleHealthFormMapper maleHealthFormMapper = session.getMapper(MaleHealthFormMapper.class);
                MaleHealthForm maleHealthForm = maleHealthFormMapper.selMaleHealthForm(employee.getId());
                System.out.println("員工體檢:"+maleHealthForm.toString());
            }else if ((employee.getSex().toString()).equals("FEMALE")){
                FemaleHealthFormMapper femaleHealthFormMapper = session.getMapper(FemaleHealthFormMapper.class);
                FemaleHealthForm femaleHealthForm = femaleHealthFormMapper.selFemaleHealthForm(employee.getId());
                System.out.println("員工體檢:"+femaleHealthForm.toString());
            }
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(session != null){
                session.close();
            }
        }
    }
}

測試結果
員工基本信息:Employee{id=3, realName='employee_3', sex=FEMALE, birthday=Sun Feb 20 00:00:00 CST 2000, mobile='18773443555', email='[email protected]', position='Programmer', note='小徐', workCard=WorkCard{id=3, empId=3, realName='employee_3', department='Tech-Dept', mobile='[email protected]', position='Programmer', note='小徐'}, employeeTaskList=[EmployeeTask{id=3, empId=3, task=Task{id=1, title='前端', context='HTML+CSS+JS+JQuery+Bootstrap+Ajax', note='前端開發'}, taskName='前端開發', note='前端'}]}
員工體檢:HealthForm{id=1, empId=3, heart='normal', liver='normal', spleen='normal', lung='normal', kidney='normal', note='***醫院'}

注意

特別注意 EmployeeMapper.xml 的映射文件
  1. association元素:對工牌進行一對一級聯,其select元素指向SQL,將通過column的id作爲參數進行傳遞,然後將結果返回給僱員POJO的屬性workCard。
  2. collection元素:一對多級聯,其select元素指向SQL,將通過column的id作爲參數進行傳遞,然後將結果返回給僱員POJO的屬性employeeTaskList。
  3. discrimination元素:鑑別器,它的屬性column的值代表使用哪個字段進行鑑別,這裏的是sex,而它的子元素case,則用於進行區分,類似於java中的switch…case…語句。而resultMap屬性表示採用哪個ResultMap去映射,比如sex=1,則使用maleHealthFormMap進行映射。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章