Mybatis中使用左连接查询-vo方式

上篇博客中写道连接查询的方法是使用了collection标签进行映射,但这样配置的话会特别的麻烦,而且这种方式用的很少,所以今天来教大家一种简单的方式来实现连接查询

首先还是看一下我们的Student表和Teacher表

Student

Teacher

然后在实体类中声明他们的字段,这里我就不演示了,直接跳过

接下来最重要的一步,我们需要将这两个表的字段放到一个实体类中,用于返回的结果。

那么我们在model包下创建一个vo包,声明一个StudentVo类

 然后看一下StudentVo里的字段

 将他们表中的字段统一加进去之后,加上Get/Set/ToString

开始我们的操作:

StudentMapper:

package com.ywt.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ywt.mybatisplus.model.Student;
import com.ywt.mybatisplus.model.vo.StudentVo;

import java.util.List;

public interface StudentMapper extends BaseMapper<Student> {

    List<StudentVo> queryAllData(Long id);
}

Mapper.xml:

    <select id="queryAllData" resultType="com.ywt.mybatisplus.model.vo.StudentVo">
        SELECT
            b.id,
            a.s_name,
            a.t_id
        FROM
            student a
                LEFT JOIN teacher b ON a.t_id = b.id
        WHERE
            b.id = #{id}
    </select>

我们根据老师id来查询每个老师对应的学生

注意:resultType的返回值是我们定义的StudentVo类

接下来在Test中测试一下

package com.ywt.mybatisplus;


@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired
    public UserMapper userMapper;

    @Test
    void queryWrapper(){
        Long id = 2L;
        List<StudentVo> studentVos = studentMapper.queryAllData(id);
        studentVos.forEach(System.out::println);
    }


}

我使用的是Long类型,后面需要加L,如果是int或Integer类型的话,不需要加L(萌新知识点)

然后我们运行方法看看是什么结果:

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值