赞
踩
<association></association>
标签通常多用于多表查询关系映射中的一对一和多对一,生成的是外部对象
<collection></collection>
标签通常多用于多表查询关系映射中的一对多,生成的是集合
多个员工对应一个部门,且每个员工隶属一个部门。站在员工角度而言,其就是一个典型的多对一关系,可以使用association
标签进行映射,相当于一个部门,里面存放该员工所属部门
两表连接查询方式
<resultMap id="empMap" type="com.mybatis.bean.Employee">
<id column="emp_id" property="empId"></id>
<result column="emp_name" property="empName"></result>
<!--association映射员工表里的部门属性Department dept-->
<association column="d_id" property="dept" javaType="com.mybatis.bean.Department">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
</association>
</resultMap>
对应SQL语句:
select e.* from employee e left join dept d on e.d_id = d.dept_id
SQL语句嵌套方式
<resultMap id="empMap" type="com.mybatis.bean.Employee">
<id column="emp_id" property="empId"></id>
<result column="emp_name" property="empName"></result>
<!--association映射员工表里的部门属性Department dept-->
<association column="d_id"
property="dept"
javaType="com.mybatis.bean.Department"
select="com.mybatis.mapper.DepartmentMapper.getDept">
<!--select属性指定连接查询的方法地址-->
</association>
</resultMap>
对应分离SQL语句:
select * from employee
select * from dept where dept_id = #{d_id}
一个部门对应多个员工,且每个员工隶属一个部门。站在部门角度而言,其就是一个典型的一对多关系,可使用collection
标签进行映射,相当于一个List集合,里面存放所有隶属于此部门的员工
两表连接查询方式
<!--映射关系,column表示数据库字段,property表示JavaBean字段-->
<resultMap id="deptMap" type="com.mybatis.bean.Department">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
<!--特别的,外部对象属性:private List<Employee> emps-->
<collection property="emps" javaType="java.util.ArrayList" ofType="com.mybatis.bean.Employee">
<id column="emp_id" property="empId"></id>
<result column="emp_name" property="empName"></result>
</collection>
</resultMap>
select d.* from dept d left join employee e on e.d_id = d.dept_id
SQL语句嵌套方式
<!--映射关系,column表示数据库字段,property表示JavaBean字段-->
<resultMap id="deptMap" type="com.mybatis.bean.Department">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
<!--映射外部对象属性:private List<Employee> emps-->
<collection property="emps" column="dept_id"
javaType="java.util.ArrayList"
ofType="com.mybatis.bean.Employee"
select="com.mybatis.mapper.EmployeeMapper.getEmpsByDeptId">
<!--通过select标签引入外部查询方法-->
</collection>
</resultMap>
对应分离SQL语句:
select * from employee where d_id = #{dept_id}
select * from dept
详细使用方法请转至 https://blog.csdn.net/weixin_46002478/article/details/108545775
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。