Javaweb-多表关系与员工查询
web后端开发进阶
一、多表关系
1.多表关系
1
2
3一对多(多对一)
一对一
多对多
2.解决方案
一对多
- 在数据库表中多的一方,添加字段,来关联一的一方的主键
一对一
- 在某一方添加一个字段,关联对方的主键(并且设置为unique)
多对多
- 需要新创建一个表实现

3.物理外键
现在已经不推荐,使用逻辑外键
1
2
3
4
5
6
7
8
9俩种添加方式
-- 创建表时指定
create table 表名(
字段名 数据类型,
...
[constraint] [外键名称] foreign key (外键字段名) references 主表 (字段名)
);
-- 建完表后,添加外键
alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(字段名);也可以使用图形化界面添加
通过右击表,点击showdiagram可以展现俩张表直接关系
使用物理外键约束后,更新父表会受限,从而保证数据一致性
二、多表查询
1.定义
多表查询: 指从多张表中查询数据
直接使用
select * from dept,emp;会出现笛卡尔积- 即将所有情况全部组合
加入约束,
select * from dept,emp where dept.id = emp.dept_id;即可获取正常结果
2.分类
连接查询
内连接(查询交集部分级)
隐式内连接
查询交集部分级 select * from dept,emp where dept.id = emp.dept_id;1
2
3
4
5
6
* **显式内连接**
* ~~~java
select emp.name,dept.name from emp inner join dept on emp.dept_id = dept.id;
inner可以省略
外连接
左外连接与右外连接 完全查询左边与完全查询右边 select 字段列表 from 表1 left [outer] join 表2 on 连接条件 ...; select emp.name,dept.name from emp left join dept on emp.dept_id = dept.id;1
2
3
4
5
6
7
8
9
10
11
12
13
14
* **将左边的全部挑出,同时右侧字段可以使用**
* **左右外连接可以互相转化**
* **子查询(SQL语句中嵌套select语句,称为嵌套查询,又称子查询。)**
* **标量子查询**
* ~~~sql
查询最早入职员工
select * from emp where entry_date = (select min(entry_date) from emp)列子查询
select emp.name,dept.name from emp,dept where emp.dept_id=dept.id and dept_id in (select id from dept where name = '教研部' or name = '咨询部'); 返回一个列1
2
3
4
5
6
* **行子查询**
* ~~~sql
select * from emp where (job,salary) = (select job,salary from emp where name = '李忠');
返回一行
表子查询
select * from emp e,(select dept_id,max(salary) max from emp group by dept_id) a where a.dept_id = e.dept_id and a.max = e.salary; 返回一个表1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
## 三、员工管理接口
* **包设置**
* <img src="https://chuanchua.oss-cn-beijing.aliyuncs.com/markdown/image-20251102212055048.png" alt="image-20251102212055048" />
### 1.分页查询
* **语句准备**
* ~~~sql
select count(*) from emp e left join dept d on e.dept_id = d.id;
select * from emp e left join dept d on e.dept_id = d.id limit ?,?;
具体实现
创建实体类封装具体每页数据
public class PageResult { private Long total; //总记录数 private List<Emp> list; //当前页数据列表 }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
* **具体代码实现**
* ~~~java
mapper
@Mapper
public interface EmpMapper {
@Select("select count(*) from emp e left join dept d on e.dept_id = d.id")
public Long count();
@Select("select e.*, d.name dept_name from emp e left join dept d on e.dept_id = d.id" +
" order by e.update_time desc limit #{start}, #{pageSize}")
public List<Emp> list(Integer start, Integer pageSize);
}controller @Slf4j @RequestMapping("/emp") @RestController() public class EmpController { @Autowired EmpService empService; @GetMapping public Result getEmp(@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "10")Integer pageSize){ log.info("查询员工,参数:{},{}",page,pageSize); PageResult<Emp> pageResult = empService.getEmp(page,pageSize); return Result.success(pageResult); } }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
* ~~~java
service
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpMapper empMapper;
@Override
public PageResult<Emp> getEmp(Integer page, Integer pageSize) {
Long total = empMapper.count();
Integer start = (page - 1) * pageSize;//起始页码计算
List<Emp> list = empMapper.list(start, pageSize);
PageResult<Emp> pageResult = new PageResult<>();
pageResult.setTotal(total);
pageResult.setList(list);
return pageResult;
}
}
pagehelper插件实现
引入依赖
<!--分页插件PageHelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.7</version> </dependency>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
* **添加插件之后mapper不需要考虑任何与分页查询相关的操作**
* **代码实现**
* ~~~java
//主要在service层
public PageResult<Emp> getEmp(Integer page, Integer pageSize) {
PageHelper.startPage(page, pageSize);
//设置参数
List<Emp> list = empMapper.list();
Page<Emp> page1 = (Page<Emp>) list;
//调用mapper接口方法
return new PageResult<>(page1.getTotal(),page1.getResult());
//返回调用对象
}
注意点
- sql语句不能加分号
- 仅对跟在后面的第一个sql语句查询生效
原理
a.select count(0) from emp e …
b.select … from emp e … limit ?,?
拦截修改sql语句
2.条件分页查询
知识点
字符串拼接
在查询条件时如果有需要用到引号,可以使用concat函数
'%#{name}%' concat('%', #{name}, '%')1
2
3
4
5
6
7
* **日期时间类型封装**
* ~~~java
使用springboot注解
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime end
传参优化
- 可以用一个实体类封装传参数据
动态sql
sql语句随外部变化
if标签,and语句会报错,不推荐1
2
3
* ~~~java
where标签,自动进行封装,推荐<where> <if test="name != null"> e.name like concat('%', #{name}, '%') </if> <if test="gender != null"> and e.gender = #{gender} </if> <if test="start != null and end != null"> and e.entry_date between #{start} and #{end} </if> </where>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
*
* **具体实现**
* ~~~java
mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
<select id="list" resultType="com.itheima.pojo.Emp">
select e.*, d.name dept_name from emp e left join dept d on e.dept_id = d.id
<where>
<if test="name != null">
e.name like concat('%', #{name}, '%')
</if>
<if test="gender != null">
and e.gender = #{gender}
</if>
<if test="begin != null and end != null">
and e.entry_date between #{begin} and #{end}
</if>
</where>
order by e.update_time desc
</select>
</mapper>
一个小知识点, Closing non transactional SqlSession通常是sql语言配置文件出错
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 十七.!