SpringBoot进行多表查询功能的实现

实体类:
【SpringBoot进行多表查询功能的实现】Emp 类:

@Data@NoArgsConstructor@AllArgsConstructorpublic class Emp {private int id; private String lastname; private String email; private int gender; private int did; private Dept dept; private Date birth = new Date(); }

Dept类:
@Data@AllArgsConstructor@NoArgsConstructorpublic class Dept {private int id; private String dname; }

Mapper接口
EmpMapper:
//这个注解表示这是一个mybatis的mapper类@Mapper@Repositorypublic interface EmpMapper {void addEmp(Emp emp); void deleteEmp(int id); void updateEmp(Emp emp); Emp queryEmpById(int id); List queryEmpList(); }

DeptMapper:
@Mapper@Repositorypublic interface DeptMapper {List queryDeptList(@Param("cid") int cid); }

EmpMapper.xml 配置文件
select * from emp_dept.employees

DeptMapper.xml配置文件
select * from emp_dept.department where id = #{id};

前端页面(部分)
编辑删除

查询结果:
SpringBoot进行多表查询功能的实现
文章图片

上述我们采用的是分步查询。
我们下面使用association嵌套映射
其实这里查询会出现一个奇怪的事情,
SpringBoot进行多表查询功能的实现
文章图片

SpringBoot进行多表查询功能的实现
文章图片

因为我们现在两个表中都有id这个字段,所以我们在映射时使用去查找部门的id时就发现查出来的是员工的id,就是因为员工的id与部门的id字段名重名了?
EmpMapper:
select emp.*,dept.* from emp_dept.employees emp,emp_dept.department dept where emp.did = dept.id

上述执行结果如下
SpringBoot进行多表查询功能的实现
文章图片

我们发现是员工id,我们现在将数据库中部门表的id改为pid
SpringBoot进行多表查询功能的实现
文章图片

修改配置文件以及实体类
@Data@AllArgsConstructor@NoArgsConstructorpublic class Dept {private int pid; private String dname; }

select emp.*,dept.* from emp_dept.employees emp,emp_dept.department dept where emp.did = dept.pid

执行结果:
SpringBoot进行多表查询功能的实现
文章图片

我们就发现查询的就是部门的id了
SpringBoot进行多表查询功能的实现
文章图片

但是针对上面这个问题我们将部门的id字段名改为did (did在员工表中也存在) 此时我们再去查询又发现还是可以把部门id查询出来
SpringBoot进行多表查询功能的实现
文章图片

这个问题就离谱,难道是因为id是主键,did不是主键的原因?就离谱
到此这篇关于SpringBoot进行多表查询的文章就介绍到这了,更多相关SpringBoot多表查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读