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); ListqueryEmpList(); }
DeptMapper:
@Mapper@Repositorypublic interface DeptMapper {ListqueryDeptList(@Param("cid") int cid); }
EmpMapper.xml 配置文件
select * from emp_dept.employees
DeptMapper.xml配置文件
select * from emp_dept.department where id = #{id};
前端页面(部分)
编辑删除
查询结果:

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

文章图片

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

文章图片
我们发现是员工id,我们现在将数据库中部门表的id改为pid

文章图片
修改配置文件以及实体类
@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
执行结果:

文章图片
我们就发现查询的就是部门的id了

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

文章图片
这个问题就离谱,难道是因为id是主键,did不是主键的原因?就离谱
到此这篇关于SpringBoot进行多表查询的文章就介绍到这了,更多相关SpringBoot多表查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- Activiti(一)SpringBoot2集成Activiti6
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- springboot使用redis缓存
- 怎么将桌面上的CAD图纸添加到软件中进行BMP格式转换()
- R语言迹检验协整关系式_使用R语言进行协整关系检验
- R|R for data Science(六)(readr 进行数据导入)
- 使用Promise对微信小程序wx.request请求方法进行封装
- springboot整合数据库连接池-->druid