表与表 一对多或者多对一 关联查询时 默认的映射规则不满足,就自定义映射规则。
规律:外键在哪儿,多方就在哪儿。
表t_department
表t_employee
两个表的关联 t_department.manager_id = t_employee.id
1.多对一例子:
准备2个表的domain
/**
* 部门实体对象
*/
@Data
public class Department {
private Long id;
//部门编号
private String sn;
//部门名称
private String name;
//部门状态 0删除,1正常
private Integer state;
//部门经理 t_department.manager_id = t_employee.id
private Employee manager;
//上级部门 t_department d t_department p d.parent_id = p.id
private Department parent;
}
/**
* 部门经理实体对象
*/
@Data
public class Employee {
private Long id;
private String username;
}
准备*mapper.xml中的sql语句
<!--
自定义映射规则:多对一 根据domain来写
多个部门对应一个上级部门
多个部门对应一个部门经理
-->
<resultMap id="deptLoadEmp" type="Department"><!--type: 主表对应domain的类型-->
<id column="id" property="id" />
<result column="sn" property="sn" />
<result column="name" property="name" />
<result column="state" property="state" />
<!--
domain中关联其他表的属性
property:对应domain中的 属性
javatype:对应domain中属性的 类型
-->
<association property="manager" javatype="Employee">
<id column="eid" property="id"/>
<result column="eusername" property="username"/>
</association>
<association property="parent" javatype="Department">
<id column="pid" property="id"/>
<result column="pname" property="name"/>
</association>
</resultMap>
<select id="loadAllDepartments" resultMap="deptLoadEmp" >
select d.*,e.id eid,e.username eusername,p.id pid,p.name pname from t_department d
left join t_employee e on d.manager_id=e.id
left join t_department p on d.parent_id=p.id
</select>
2.一对多的例子
准备2张表
t_employee
<cltoin… ofType>