???自信攻城狮小名又来攻城啦???
书接上文,在上一篇,小名给大家演示了三种
MP 的单表查询方式,今天这篇文章的小名想给大家演示一下关于
MP 多表查询的相关操作。
1. 一篇朴实无华的MyBatis-Plus小白看完原地进阶的文章 2. 【CRUD】番外篇 3. 此专栏下其他文章
数据表 practice_user:
practice_teacher:
公用部分:
1. VO
@Data
public class TeacherAndUserVo extends PracticeTeacher{
@ApiModelProperty(value = "User名字")
private String name;
@ApiModelProperty(value = "User性别")
private String sex;
}
2. PracticeTeacherService
List<TeacherAndUserVo> selectTeacherAndUserVoBySql();
List<TeacherAndUserVo> selectTeacherAndUserVoByForeach();
List<TeacherAndUserVo> selectTeacherAndUserVoByStream();
一、SQL
1. PracticeTeacherMapper.xml
<select id="selectTeacherAndUserVoBySql" resultType="eamon.daily.practice.teacher.entity.vo.TeacherAndUserVo">
SELECT
`user`.`name`,
`user`.sex,
teacher.*
FROM
`practice_teacher` teacher
LEFT JOIN practice_user `user` ON teacher.user_id = `user`.id
where `user`.sex="女"
</select>
2. PracticeTeacherMapper.java
List<TeacherAndUserVo> selectTeacherAndUserVoBySql();
3. PracticeTeacherServiceImpl.java
@Resource
PracticeTeacherMapper practiceTeacherMapper;
@Override
public List<TeacherAndUserVo> selectTeacherAndUserVoBySql() {
return practiceTeacherMapper.selectTeacherAndUserVoBySql();
}
4. 结果:
众所周知:mybatis-plus的条件构造器、链式查询只能单表查询
下面小名给大家说点不一样的吧😏
二、链式调用 lambda 式,lambdaQuery()+foreach
(不了解lambdaQuery()的小伙伴见:【CRUD1】简单单表查询)
1. PracticeTeacherServiceImpl.java
@Autowired
IPracticeTeacherService practiceTeacherService;
@Autowired
IPracticeUserService practiceUserService;
@Override
public List<TeacherAndUserVo> selectTeacherAndUserVoByForeach() {
List<PracticeTeacher> teachers = practiceTeacherService.lambdaQuery().list();
ArrayList<TeacherAndUserVo> teacherAndUserVos = new ArrayList<>();
for (PracticeTeacher teacher : teachers) {
PracticeUser woman = practiceUserService.lambdaQuery()
.eq(PracticeUser::getSex, "女")
.eq(PracticeUser::getId, teacher.getUserId())
.one();
if(woman!=null){
TeacherAndUserVo copy = CopyUtil.copy(teacher, TeacherAndUserVo.class);
copy.setName(woman.getName());
copy.setSex(woman.getSex());
teacherAndUserVos.add(copy);
}
}
return teacherAndUserVos;
}
2. 结果
下面咱们再搞点“高端操作”吧
咱们尝试用lambda表达式来实现上面foreach的效果
三、stream
1. PracticeTeacherServiceImpl.java
@Override
public List<TeacherAndUserVo> selectTeacherAndUserVoByStream() {
List<PracticeTeacher> teachers = practiceTeacherService.lambdaQuery().list();
List<PracticeUser> womans = practiceUserService.lambdaQuery().eq(PracticeUser::getSex, "女").list();
List<TeacherAndUserVo> teacherAndUserVos = womans.stream().map(
o -> {
TeacherAndUserVo vo = new TeacherAndUserVo();
for (PracticeTeacher teacher : teachers) {
if (teacher.getUserId().longValue() == o.getId()) {
vo = CopyUtil.copy(teacher, TeacherAndUserVo.class);
vo.setName(o.getName());
vo.setSex(o.getSex());
}
}
return vo;
})
.filter(x -> x.getName() != null)
.collect(Collectors.toList());
return teacherAndUserVos;
}
这个例子不是很恰当,小名只是为了给大家演示一下lambda的用法。
2. 结果
完事儿~收工!
如果觉得小名的文章帮助到了您,请关注小名的新专栏
MyBatis-Plus【CRUD】,支持一下小名😄,给小名的文章点赞👍、评论?、收藏🤞谢谢大家啦~???
|