MyBatis专栏5 - 关联查询之一对一

一(多)对一

1.需求

​ 本次案例以简单的用户和账户的模型来分析 Mybatis 多表关系。用户为 User 表,账户为Account 表。一个用户(User)可以有多个账户(Account),但是一个账户(Account)只能属于一个用户(User)。

查询所有账户信息, 关联查询账户的用户名和地址

​ 因为一个账户信息只能供某个用户使用,所以从查询账户信息出发关联查询用户信息为一对一查询。

  • 数据库的准备
CREATE TABLE t_account(
		aid INT PRIMARY KEY auto_increment,
		money DOUBLE,
		uid INT
);
ALTER TABLE t_account ADD FOREIGN KEY(uid) REFERENCES t_user(uid);

INSERT INTO `t_account` VALUES (null, '1000', '1');
INSERT INTO `t_account` VALUES (null, '2000', '1');
INSERT INTO `t_account` VALUES (null, '1000', '2');
INSERT INTO `t_account` VALUES (null, '2000', '2');
INSERT INTO `t_account` VALUES (null, '800', '3');

2.分析

  • 查询语句
select * from t_user u,t_account a where a.uid=u.uid and u.uid=#{uid}

3.实现

  • 修改Account.java

    在 Account 类中加入 User类的对象作为 Account 类的一个属性。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account implements Serializable {
    private Integer aid;
    private Double money;
    private Integer uid;
    /**
     * 表示Account和User的一对一关系
     */
    private User user;
}
  • AccountDao.java

public interface AccountDao {
    /**
     * 根据账户的aid查询出账户信息,并且连接t_user表获取该账户的用户信息
     * @param aid
     * @return
     */
    Account findAccountUserByAid(int aid);
}
  • AccountDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.AccountDao">
    <!--
        使用resultMap标签自定义映射规则
    -->
    <resultMap id="accountUserMap" type="Account">
        <id column="aid" property="aid"></id>
        <result column="money" property="money"></result>
        <result column="uid" property="uid"></result>

        <!--
            要进行一对一的映射配置
            property表示要映射的pojo的属性名
            javaType表示要进行映射的POJO的属性的类型
        -->
        <association property="user" javaType="User">
            <result column="uid" property="uid"></result>
            <result column="username" property="username"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
            <result column="address" property="address"></result>
        </association>
    </resultMap>
    <select id="findAccountUserByAid" parameterType="int" resultMap="accountUserMap">
        select * from t_account a,t_user u where a.uid=u.uid and a.aid=#{aid}
    </select>
</mapper>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

能力工场小马哥

如果对您有帮助, 请打赏支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值