MyBatis关联查询(一、一对一查询)

MyBatis关联查询(一、一对一查询)

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

在第一个mybatis项目并读取数据库信息这篇博文的基础上,对数据库中的account表进行一对一关联查询

表结构如下:
MyBatis关联查询(一、一对一查询)_第1张图片

先编写account表的pojo文件

public class Account implements Serializable {

    private Integer id;
    private Integer uid;
    private Double money;
    //加入User类的对象作为Account类的一个属性
    private User user;

    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                ", user=" + user +
                '}';
    }
}

编写AccountMapper.java代码

public interface AccountMapper {
    Account getAccountById(Integer id);
}

在AccountMapper.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="cn.fpl1116.mapper.AccountMapper">
    <resultMap id="getAccountByIdResultMap" type="account">
        <id column="aid" property="id"></id>
        <result column="uid" property="uid"></result>
        <result column="money" property="money"></result>
        <!--
            一对一查询使用association标签
            property="user"Account的属性名
            javaType="user":等价于resultType
        -->
        <association property="user" javaType="user">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="birthday" property="birthday"></result>
            <result column="sex" property="sex"></result>
            <result column="address" property="address"></result>
        </association>
    </resultMap>
    <select id="getAccountById" parameterType="int" resultMap="getAccountByIdResultMap">
        SELECT a.id aid, a.money money, a.uid uid, u.* FROM account a LEFT JOIN USER u ON a.uid = u.id WHERE a.id=1
    </select>
</mapper>

编写测试方法

@Test
    public void testGetAccountById() throws IOException {
        AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
        Account account = accountMapper.getAccountById(1);
        System.out.println(account);
    }

运行结果如下:

MyBatis关联查询(一、一对一查询)_第2张图片

你可能感兴趣的:(JAVA全栈学习路线,#,MyBatis,mybatis,intellij-idea,java,sql,mysql)