Mybatis关联查询
1.一对一查询
员工表pojo
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class Emp implements Serializable {
private Integer id;
private String name;
private Integer age;
// private Integer deptId;
private Dept dept;//一个员工对应一个部门,所以使用对象封装
}
部门表pojo
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Dept implements Serializable {
private Integer deptId;
private String deptName;
private List<Emp> emps;//一个部门有多个员工,所以使用list封装
}
**查询员工表emp所对应的部门表dept。两种方式:**
1.1单条sql语句查询
<select id="findAll" resultMap="empRM">
select emp.id,emp.name,emp.age,emp.dept_id,dept.dept_name
from emp join dept on emp.dept_id=dept.dept_id
</select>
<resultMap id="empRM" type="Emp" autoMapping="true">
<id column="id" property="id"></id>
<association property="dept" javaType="Dept" >
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>
1.2多条语句查询
<select id="findAllWhere" resultMap="empRM2">
select * from emp
</select>
<resultMap id="empRM2" type="Emp" autoMapping="true">
<id column="id" property="id"/>
<association property="dept" javaType="Dept"
column="dept_id" select="findDept"/>
</resultMap>
<select id="findDept" resultMap="deptRM">
select * from dept where dept_id=#{dept_id}
</select>
<resultMap id="deptRM" type="Dept">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
</resultMap>