关于Mybatis注解开发一对一查询

之前我们在xml配置文件中实现多表查询中的一对一查询,需要写的相对注解来说比较复杂。

一、建立两张表

在这里插入图片描述

在这里插入图片描述

二、建立相应的实体类

public class Account implements Serializable {
    private int id;
    private int uid;
    private double money;
    //建立一对一的关系
    private User user;
public class User implements Serializable {
    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;

三、建立Dao

在UserDao处写一个方法待会要使用

@Select("select * from user where id = #{id}")
    User selectByID(Integer id);

AccountDao:

package com.tubai.dao;

import com.tubai.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface AccountDao {
    /**
     * 查询所有用户 并且获取每个用户所属的用户信息
     * @return
     */
    @Select("select * from account")
    @Results(id="AccountUserMapper",value={
            @Result(id=true,column = "id",property = "id"),
            @Result(column = "uid",property = "uid"),
            @Result(column = "money",property = "money"),
            @Result(column = "uid",property = "user",
                    one=@One(select = "com.tubai.dao.UserDao.selectByID",fetchType = FetchType.EAGER))
    })
    List<Account> selectAll();
}

我们发现写法与我们在xml配置文件中的写法是类似的

我们解释这行相对陌生的代码

@Result(column = "uid",property = "user",
                    one=@One(select = "com.tubai.dao.UserDao.selectByID",fetchType = FetchType.EAGER))

column是数据库中的列名 property是类的属性名

同时column也是我们通过ID查询方法中的参数

one属性代表是一对一查询

注解@One的源码
	public @interface One {
    String select() default "";

    FetchType fetchType() default FetchType.DEFAULT;
}

其中select代表我们要调用哪个包下的哪个类的哪个方法

fetchType我们点开源码 发现是个枚举

public enum FetchType {
    LAZY,
    EAGER,
    DEFAULT;

    private FetchType() {
    }
}

表示加载的方式 是延迟加载,立即加载 亦或者是默认选择

四、运行即可

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值