框架学习-1.Mybatis-7. Mybatis多表关系查询

7. Mybatis多表关系 总览

参考狂神说MyBatis课程笔记

参考黑马程序员MyBaits课程笔记

MyBatis笔记思维导图:

思维导图笔记链接

问题扩展与汇总:

1.多对一(一对一)

1)多对一(一对一)的理解:

需求
  • Mybatis多对一的操作,与一对一相同,均是主表一条数据关联从表一条数据
  • 例如:个人信息与账户信息,一个人有多个账号信息
    • 对于,账号信息来说,就是多对一,具体到一个账号信息,就是一对一
    • 即,查询所有账户信息,关联查询下单用户信息
      • 因为一个账户信息只能供某个用户使用,所以从查询账户信息出发关联查询用户信息为一对一查询。
      • 如果从用户信息出发查询用户下的账户信息则为一对多查询,因为一个用户可以有多个账户。
操作验证步骤

在这里插入图片描述

2)数据库设计与环境搭建

数据库设计

在这里插入图片描述

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` datetime default NULL COMMENT '生日',
  `sex` char(1) default NULL COMMENT '性别',
  `address` varchar(256) default NULL COMMENT '地址',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `ID` int(11) NOT NULL COMMENT '编号',
  `UID` int(11) default NULL COMMENT '用户编号',
  `MONEY` double default NULL COMMENT '金额',
  PRIMARY KEY  (`ID`),
  KEY `FK_Reference_8` (`UID`),
  CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert  into `account`(`ID`,`UID`,`MONEY`) values (1,41,1000),(2,45,1000),(3,41,2000);

在这里插入图片描述

环境搭建
创建user,count实体类
public class User {
    private int userId;
    private String username;
    private Date birthday;
    private String gender;
    private String address;
    // get、set、toStrig
}
public class Count {
    private int countId;
    private int userId;
    private double money;
    // get、set、toStrig
}
创建映射接口
public interface UserMapper {
    // 1. 查
    // 查询全部用户
    List<User> getUserList();
}
public interface CountMapper {
    // 1. 测试,查询所有账户信息
    List<Count> getCountList();
}
映射sql基本语句编写
<?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">
<!--namespace=绑定一个对应的Mapper接口-->
<mapper namespace="com.sheng.dao.UserMapper">
    <!--    定义全局变量-->
    <sql id="selectFields">
        select id, username, birthday, sex, address from user
    </sql>
    <sql id="insertFields">
        insert into user(username, birthday, sex, address) values(#{username}, #{birthday}, #{gender}, #{address})
    </sql>
<!--    定义resultMap-->
    <resultMap id="userMap" type="user">
        <!-- id为主键 -->
        <id column="id" property="userId"/>
        <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
        <result column="username" property="username"/>
        <result column="sex" property="gender"/>
        <result column="address" property="address"/>
        <result column="birthday" property="birthday"/>
    </resultMap>

<!--    查询所有用户-->
    <select id="getUserList" resultMap="userMap">
       <include refid="selectFields"></include>
    </select>
</mapper>
<?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">
<!--namespace=绑定一个对应的Mapper接口-->
<mapper namespace="com.sheng.dao.AccountMapper">
    <!--    定义全局变量-->
    <sql id="selectFields">
        select id, uid, money from account
    </sql>
    <sql id="insertFields">
        insert into account(uid, money) values(#{userId}, #{money})
    </sql>

<!--    定义resultMap-->
    <resultMap id="accountUserMap" type="account">
        <!-- id为主键 -->
        <id column="id" property="id"/>
        <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
        <result column="uid" property="userId"/>
        <result column="money" property="money"/>
    </resultMap>

<!--    查询所有用户-->
    <select id="getUserList" resultMap="accountUserMap">
       <include refid="selectFields"></include>
    </select>

</mapper>
测试
public class UserMapperTest {
    private SqlSession sqlSession;
    private UserMapper userMapper;

    @Before//用于在测试方法执行之前执行
    public void init() throws Exception {
        // 获得SqlSession对象
        sqlSession = MybatisUtils.getSqlSession();
        //4.获取dao的代理对象
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy() throws Exception {
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
    }

    @Test
    public void test() {
        List<User> userList = userMapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}
ublic class AccountMapperTest {
    private SqlSession sqlSession;
    private AccountMapper accountMapper;

    @Before//用于在测试方法执行之前执行
    public void init() throws Exception {
        // 获得SqlSession对象
        sqlSession = MybatisUtils.getSqlSession();
        //4.获取dao的代理对象
        accountMapper = sqlSession.getMapper(AccountMapper.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy() throws Exception {
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
    }

    @Test
    public void test() {
        List<Account> accountList = accountMapper.getAccountList();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }
}

3)方式一:按查询嵌套处理(子查询)

添加引用
  • 从表(多个数据)的表中添加主表对象(对应一条数据)的引用
//    持有主表对象的引用
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
接口中定义方法
  • 在接口中定义查询账户和关联用户信息的方法
  • 因为 Account 类中包含了一个 User 类的对象,它可以封装账户所对应的用户信息。
// 2.多表查询-多对一-查询账户和关联用户信息
// 方式一:按查询嵌套处理
List<Account> getAccountUser1();
编写sql语句
  • 封装返回结果,故需要使用resultMap

  • User属性是一个类,复杂类型,Mybatis有特殊处理

    • association 标签处理对象,用于多对一,一对一查询
      • association关联属性
      • property属性名
      • javaType属性类型
      • column 表中外键的字段名
      • select 子查询的id名
    • collection 标签处理集合,用于一对多,或是多对多查询
      • ofType 用于指定集合元素的数据类型
    <!--    2.多表查询-多对一-查询账户和关联用户信息-按查询嵌套-->
        <resultMap id="accountUserMap1" type="account">
            <!-- id为主键 -->
            <id column="id" property="accountId"/>
            <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
            <result column="uid" property="userId"/>
            <result column="money" property="money"/>
            <association property="user" javaType="user" column="uid" select="getUser"></association>
        </resultMap>
    
        <select id="getAccountUser" resultMap="accountUserMap1">
            <include refid="selectFields"></include>
        </select>
        <select id="getUser" resultType="user">
            select * from user where id = #{userId}
        </select>
    
    --------每个account的信息------------
    Account{accountId=1, userId=41, money=1000.0}
    User{userId=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, gender='男', address='北京'}
    --------每个account的信息------------
    Account{accountId=2, userId=45, money=1000.0}
    User{userId=45, username='李四', birthday=Sun Mar 04 12:04:06 CST 2018, gender='男', address='天津'}
    --------每个account的信息------------
    Account{accountId=3, userId=41, money=2000.0}
    User{userId=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, gender='男', address='北京'}
    

    4)方式二:按结果嵌套处理(联表查询)

接口中定义方法
  • 在接口中定义查询账户和关联用户信息的方法
  • 因为 Account 类中包含了一个 User 类的对象,它可以封装账户所对应的用户信息。
// 2.多表查询-多对一-查询账户和关联用户信息
// 方式二:按结果嵌套处理
List<Account> getAccountUser2();
编写sql语句及测试
  • 注意多表联接查询两个表字段名相同时,要给字段取别名,否则,封装结果会出错
    • 即,a.id as aid,区别封装
    • 相应的resultMap封装,字段名也要改
<!--方式二:按结果嵌套(多表查询)-->
<resultMap id="accountUserMap2" type="account">
    <!-- id为主键 -->
    <id column="aid" property="accountId"/>
    <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
    <result column="uid" property="userId"/>
    <result column="money" property="money"/>
    <association property="user" javaType="user">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
        <result column="birthday" property="birthday"/>
    </association>
</resultMap>

<select id="getAccountUser2" resultMap="accountUserMap2">
    select a.id aid,a.uid,a.money, u.* from account a,user u where a.uid =u.id;
</select>
//    方式二:按结果嵌套(联表查询)
accounts = accountMapper.getAccountUser2();
for(Account account : accounts) {
    System.out.println("--------每个account的信息------------");
    System.out.println(account);
    System.out.println(account.getUser());
}

在这里插入图片描述

2. 一对多

需求

  • 查询所有用户信息及用户关联的账户信息

按结果嵌套处理

添加引用

  • 一对多,添加从表集合的引用
// 一对多,添加从表集合的引用
private List<Account> accounts;

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

public void setAccounts(List<Account> accounts) {
    this.accounts = accounts;
}
接口定义方法
// 多表查询-一对多
List<User> getUserAccount();
编写sql语句及测试

核心sql语句:

  • # 左联接
    select u.*,a.id as aid ,a.uid,a.money from user u
                left outer join account a on u.id = a.uid
    

User属性是一个类,复杂类型,Mybatis有特殊处理

  • association 标签处理对象,用于多对一,一对一查询

    • association关联属性
    • property属性名
    • javaType属性类型
    • column 表中外键的字段名
    • select 子查询的id名
  • collection 标签处理集合,用于一对多,或是多对多查询

    • ofType 用于指定集合元素的数据类型
    <!--    多表查询-一对多-查询用户和关联的账户信息-->
        <resultMap id="userAccountMap" type="user">
            <!-- id为主键 -->
            <id column="id" property="id"/>
            <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
            <result column="username" property="username"/>
            <result column="sex" property="sex"/>
            <result column="address" property="address"/>
            <result column="birthday" property="birthday"/>
            <collection property="accounts" ofType="account">
                <id column="aid" property="accountId"/>
                <result column="uid" property="userId"/>
                <result column="money" property="money"/>
            </collection>
        </resultMap>
        
        <select id="getUserAccount" resultMap="userAccountMap">
            select u.*,a.id as aid ,a.uid,a.money from user u
                left outer join account a on u.id = a.uid
        </select>
    
    -----每个用户的信息------
    User{userId=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, gender='男', address='北京'}
    [Account{accountId=1, userId=41, money=1000.0}, Account{accountId=3, userId=41, money=2000.0}]
    -----每个用户的信息------
    User{userId=45, username='李四', birthday=Sun Mar 04 12:04:06 CST 2018, gender='男', address='天津'}
    [Account{accountId=2, userId=45, money=1000.0}]
    ...
    

    在这里插入图片描述

3. 多对多

需求及关系模型

用户与角色的多对多关系模型
  • 一个用户可以对应多个角色
  • 一个角色可以对应多个用户
  • 需要用中间表来处理多对多的关系

在这里插入图片描述

需求
  • 查询所有角色,并同时获取角色所赋予的用户信息
  • 或者查询所有用户,并同时获取用户所扮演的角色信息
  • 需要通过中间表来进行处理

在这里插入图片描述

实现Role到User的多对多

  • 实质还是处理一对多的实现,是双向的一对多的实现
实体类创建、添加引用
public class Role {
    private int id;
    private String roleName;
    private String roleDesc;

    //多对多的关系映射:一个角色可以赋予多个用户
    private List<User> users;
    // get、set...
}
接口方法定义
// 1.多表查询-多对多
List<Role> getRoleUser();
sql编写及测试
<!--    1.多表查询-多对多-查询所有角色及关联的用户信息-->
    <resultMap id="roleUserMap" type="role">
        <id column="rid" property="id"/>
        <result column="role_name" property="roleName"/>
        <result column="role_desc" property="roleDesc"/>
        <collection property="users" ofType="user">
            <id column="id" property="id"/>
            <result column="username" property="username"/>
            <result column="sex" property="sex"/>
            <result column="address" property="address"/>
            <result column="birthday" property="birthday"/>
        </collection>
    </resultMap>

    <select id="getRoleUser" resultMap="roleUserMap">
        select u.*,r.id as rid,r.role_name,r.role_desc from role r
        left join user_role ur on r.ID = ur.RID
        left join user u on ur.UID = u.id
    </select>
//    1.多表查询-多对多-查询角色和关联的用户信息
    @Test
    public void testGetAccountUser() {
        List<Role> roles = roleMapper.getRoleUser();
        for(Role role : roles) {
            System.out.println("--------每个角色的信息------------");
            System.out.println(role);
            System.out.println(role.getUsers());
        }
    }
}
Role{id=1, roleName='院长', roleDesc='管理整个学院'}
[User{userId=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, gender='男', address='北京'}, User{userId=45, username='李四', birthday=Sun Mar 04 12:04:06 CST 2018, gender='男', address='天津'}]
--------每个角色的信息------------
Role{id=2, roleName='总裁', roleDesc='管理整个公司'}
[User{userId=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, gender='男', address='北京'}]
--------每个角色的信息------------
Role{id=3, roleName='校长', roleDesc='管理整个学校'}
[]
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值