mybatis使用注解的方式实现子查询

数据库

create table employee(
    id int primary key,
    name varchar(20),
    salary int,
    dep_id int,
    foreign key(dep_id) references department(id)
);
create talbe department(
    id int primary key,
    name varchar(20)
);

pojo

// pojo
public class Employee {
    private Long id;

    private String name;

    private Integer salary;

    private Integer depId;

    // 通过子查询获得的属性
    private String depName;
}

需要实现的sql语句

select id,name,salary,
(select name from department where id=dep_id) depName 
from employee;

实现步骤

1. 子查询:方法参数由父查询提供

    @Select("select name from department where id = #{id}")
    String nameById(Integer id);

2. 父查询:将需要的数据都查询出来,注意子查询的查询条件dep_id也需要查询

    @Select("select id,name,salary,dep_id from tbl_employee")
    List<Employee> getAll();

3. 子查询映射

                one: 配置子查询路径   (找到子查询方法)

                column: 给子查询设置参数  (父查询查到的dep_id作为子查询的参数)

                property: 将查询结果封装到对应的pojo属性中 (子查询中的name ——> depName)

    @Select("select id,name,salary,dep_id from tbl_employee")
    @Results(value = {
            @Result(
                property = "depName", column = "dep_id", 
                one = @One(select = "com.hrm.dao.DepartmentDao.nameById"))})
    List<Employee> getAll();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值