mybatis 多对多 返回list结果集,里面再嵌套list
<resultMap type="com.backendmanager.bean.Department" id="findAll">
<id property="id" column="id" />
<result property="departmentName" column="departmentName" />
<collection property="employees" javaType="list"
ofType="com.backendmanager.bean.Employee">
<!-- 一对多出现的问题: 当数据库表中,主表的主键id和明细表的 ... 当表中的字段名相同时怎么办?多表联查? 注意:Mybatis中做多表联查的时候,不管是
一对一、一对多、一对多对多:多对多: 都不能有字段重名的情况:不管是主键还是普通字段。 一旦字段重名的话,就会造成数据少自动赋值,或者覆盖,甚至重复赋值!
规避和解决此类问题的方法: 1.尽量不要表间重名,mybatis里处理起来很麻烦!id和普通字段都是。 但是在表多的时候,很难不会出现字段重名的情况。主键id最容易重名!
那么就要用以下的办法了! 2.在mybatis中写原生SQL进行查询的时候,查的字段尽可能的少,这 也影响速率,强烈禁止使用*,用多少查多少!这样也能及时发现字段重
名的情况! 3.最后如果真的需要查出重名的字段,并且修改数据库字段名造成的更改 过大,这里推荐的方式是给字段取别名,在写resultMap映射的时候,其
中的column属性就填写SQL语句中查出字段取的别名,这样就能解决重复 问题了! -->
<id property="id" column="eid" />
<result property="lastName" column="lastname" />
<result property="email" column="email" />
<result property="gender" column="gender" />
<result property="dId" column="did" />
</collection>
</resultMap>
<select id="findAll" resultMap="findAll">
select t1.id,t1.departmentName,
t2.id as eid,t2.lastname,t2.email,t2.gender,t2.did
from Department t1 left join Employee t2 on t1.id=t2.did
</select>
package com.backendmanager.bean;
import java.io.Serializable;
import java.util.List;
public class Department implements Serializable{
private Integer id;
private String departmentName;
private List<Employee> employees;
public Department() {
super();
// TODO Auto-generated constructor stub
}
public Department(Integer id, String departmentName) {
super();
this.id = id;
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
Mybatis一对多关联查询,返回结果集list中嵌套list实例(collection实现)_守得云开见月明-CSDN博客