Mybatis的关联查询(association和collection)

关联查询

  • 实体间的关系(拥有 has、属于 belong)

    • OneToOne:一对一关系(account ←→ user)

    • OneToMany:一对多关系(user ←→ account)

    • ManyToMany:多对多关系(user ←→ role)

  • 什么是关联查询

    当访问关系的一方时,如果需要查看与之关联的另一方数据,则必须使用表链接查询,将查询到的另一方数据,保存在本方的属性中

  • 关联查询的语法

    指定“一方”关系时(对象),使用< association javaType="" >

    指定“多方”关系时(集合),使用< collection ofType="" >

一,一对一查询

需求:查询账户信息,关联查询用户信息。

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

com.by.pojo下的Account类

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 +
                '}';
    }
}

com.by.dao下的AcountDao接口

public interface AccountDao {
    List<Account> findAll();
}

com.by.dao下的AcountDao.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.by.dao.AccountDao">
    <!-- 结果映射 -->
    <!--resultMap中的id必须与select中的resultMap中的值相同-->
    <resultMap type="account" id="findAllResultMap">
        <id column="aid" property="id"/>
        <result column="uid" property="uid"/>
        <result column="money" property="money"/>
        <!-- 指定关系表中数据的封装规则 -->
        <!--
            association 处理一对一
            封装一对一信息关系的标签
            property  类的属性名
            javaType  用哪个类的对象给属性赋值

        -->
        <association property="user" javaType="user">
            <id column="id" property="id"/>
            <result column="username" property="username"/>
            <result column="sex" property="sex"/>
            <result column="birthday" property="birthday"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>
    <select id="findAll" resultMap="findAllResultMap">
        select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id
    </select>
</mapper>

测试类

private SqlSession sqlSession;
    private InputStream inputStream;
    @Before
    public void init() throws IOException {
        //加载配置文件
        String resource = "mybatis-config.xml";
        inputStream = Resources.getResourceAsStream(resource);
        //创建SessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //使用数据的会话实例
        sqlSession = sessionFactory.openSession();
    }
@After
    public void close() throws IOException {
        sqlSession.close();
        inputStream.close();
    } 
@Test
    public void testOneToOne() {
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        List<Account> accountList = accountDao.findAll();
        for (Account ac : accountList) {
            System.out.println(ac);
        }
    }

输出结果

二,一对多查询

需求:查询所有用户信息及用户关联的账户信息。

分析:用户信息和他的账户信息为一对多关系,并且查询过程中如果用户没有账户信息,此时也要将用户信息查询出来,此时左外连接查询比较合适。

com.by.pojo下的Account类

package com.by.pojo;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;
    private Date birthday;
    private String sex;
    private String address;
    //加入List<Account>存储用户所拥有的账户
    private List<Account> accounts;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", accounts=" + accounts +
                '}';
    }
}

com.by.dao下的AcountDao接口

public interface AccountDao {
    List<Account> findAll();
}

com.by.dao下的UserDao.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.by.dao.UserDao">
    <!--resultMap中的id必须与select中的resultMap中的值相同-->
    <resultMap type="user" id="findAllResultMap">
        <id column="id" property="id"></id>
        <result column="username" property="username"/>
        <result column="address" property="address"/>
        <result column="sex" property="sex"/>
        <result column="birthday" property="birthday"/>
        <!-- collection 是用于建立一对多中集合属性的对应关系
        ofType 用于指定集合元素的数据类型
        -->
        <collection property="accounts" ofType="account">
            <id column="aid" property="id"/>
            <result column="uid" property="uid"/>
            <result column="money" property="money"/>
        </collection>
    </resultMap>
    <!-- 配置查询所有操作 -->
    <select id="findAll" resultMap="findAllResultMap">
      select u.*,a.id as aid ,a.uid,a.money 
      from user u left join account a on u.id =a.uid
    </select>
</mapper>

测试类

private SqlSession sqlSession;
    private InputStream inputStream;
    @Before
    public void init() throws IOException {
        //加载配置文件
        String resource = "mybatis-config.xml";
        inputStream = Resources.getResourceAsStream(resource);
        //创建SessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //使用数据的会话实例
        sqlSession = sessionFactory.openSession();
    }
@After
    public void close() throws IOException {
        sqlSession.close();
        inputStream.close();
    }
@Test
    public void testOneToMany() {
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.findAll();
        for(User user : userList){
            System.out.println(user);
        }
    }

输出结果

三,多对多查询

需求:查询角色及角色赋予的用户信息。

分析:一个用户可以拥有多个角色,一个角色也可以赋予多个用户,用户和角色为双向的一对多关系,多对多关系其实我们看成是双向的一对多关系。

 com.by.pojo下的Role类

public class Role {
    private Integer id;
    private String roleName;
    private String roleDesc;
    //加入List<User> users存储角色赋予的用户信息
    private List<User> users;

    public Integer getId() {
        return id;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                ", users=" + users +
                '}';
    }
}

com.by.dao下的RoleDao接口

public interface RoleDao {
    List<Role> findAll();
}

com.by.dao下的RoleDao.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.by.dao.RoleDao">
    <!--定义 role 表的 ResultMap-->
    <resultMap id="findAllResultMap" type="Role">
        <id property="id" column="rid"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
        <collection property="users" ofType="user">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </collection>
    </resultMap>
    <!--查询所有-->
    <select id="findAll" resultMap="findAllResultMap">
        select r.id as rid,r.role_name,r.role_desc,u.* from role r
        left join user_role ur on r.id = ur.rid
        left join user u on u.id = ur.uid
    </select>
</mapper>

测试类

private SqlSession sqlSession;
    private InputStream inputStream;
    @Before
    public void init() throws IOException {
        //加载配置文件
        String resource = "mybatis-config.xml";
        inputStream = Resources.getResourceAsStream(resource);
        //创建SessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //使用数据的会话实例
        sqlSession = sessionFactory.openSession();
    }
@After
    public void close() throws IOException {
        sqlSession.close();
        inputStream.close();
    } 
 @Test
    public void testManyToMany() {
        RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
        List<Role> roleList = roleDao.findAll();
        for(Role role : roleList){
            System.out.println(role);
        }
    }

测试结果

深入学习推荐文章: 

Mybatis中三种关联关系的实现,看这篇就够了 - 知乎 (zhihu.com) 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis Plus中的AssociationCollection都是用于多表关联查询的。其中Association用于一对一的关系,Collection用于一对多的关系。 下面是一个Association的例子: 假设我们有两个表,一个是学校表(school),另一个是班级表(class)。一个学校可以有多个班级,但一个班级只属于一个学校。我们需要查询学校信息,并且将学校下的所有班级信息也一并查询出来。 ```java public class School { private Long id; private String name; private List<Class> classes; // getter and setter } public class Class { private Long id; private String name; private Long schoolId; // getter and setter } ``` 对应的Mapper.xml文件如下: ```xml <select id="getSchoolById" resultMap="schoolResultMap"> select * from school where id = #{id} </select> <resultMap id="schoolResultMap" type="School"> <id property="id" column="id"/> <result property="name" column="name"/> <collection property="classes" ofType="Class"> <id property="id" column="id"/> <result property="name" column="name"/> <association property="school" javaType="School"> <id property="id" column="school_id"/> <result property="name" column="school_name"/> </association> </collection> </resultMap> ``` 上述代码中,我们使用了collection标签来表示一对多的关系,使用了association标签来表示一对一的关系。其中,association标签中的javaType属性表示关联的实体类类型,id标签中的column属性表示关联的字段名。 下面是一个Collection的例子: 假设我们有两个表,一个是班级表(class),另一个是学生表(student)。一个班级可以有多个学生,我们需要查询班级信息,并且将班级下的所有学生信息也一并查询出来。 ```java public class Class { private Long id; private String name; private List<Student> students; // getter and setter } public class Student { private Long id; private String name; private Long classId; // getter and setter } ``` 对应的Mapper.xml文件如下: ```xml <select id="getClassById" resultMap="classResultMap"> select * from class where id = #{id} </select> <resultMap id="classResultMap" type="Class"> <id property="id" column="id"/> <result property="name" column="name"/> <collection property="students" ofType="Student"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="classId" column="class_id"/> </collection> </resultMap> ``` 上述代码中,我们同样使用了collection标签来表示一对多的关系。注意,由于Student实体类中已经有了classId属性,因此我们不需要再使用association标签来表示一对一的关系。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

冰冰很社恐

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值