2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第1张图片
新建表account
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第2张图片
其中用户和账户是一对多的关系
在这里插入图片描述

新建实体类Account

package com.itheima.domain;

import java.io.Serializable;

/**
 * 账户实体类
 */
public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;

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

新建接口IAccountDao

package com.itheima.dao;

import com.itheima.domain.Account;
import com.itheima.domain.AccountUser;

import java.util.List;

/**
 * 账户持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有账户信息
     * @return
     */
    List<Account> findAll();

}

新建映射配置文件IAccountDao.xml



 <mapper namespace="com.itheima.dao.IAccountDao">

    
    <select id="findAll" resultType="Account">
        select * from account
    select>


mapper>

新建测试类

package com.itheima.test;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.domain.AccountUser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class AccountTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IAccountDao accountDao;

    @Before  //用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession(true);
        //4.获取dao的代理对象
        accountDao = sqlSession.getMapper(IAccountDao.class);
    }

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

        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll(){

        // 执行方法
        List<Account> accounts = accountDao.findAll();

        for (Account account : accounts) {
            System.out.println(account);
        }
    }



测试一下查询所有方法,成功
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第3张图片

实现查询账户信息时同时查询当前账户所属的用户信息(一对一的查询 )

从表实体应该包含一个主表实体的对象引用,Account实体类中应该有一个User类的引用

package com.itheima.domain;

import java.io.Serializable;

/**
 * 账户实体类
 */
public class Account implements Serializable {

    private Integer id;
    private Integer uid;
    private Double money;

    // 从表实体应该包含一个主表实体的对象引用
    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 +
                '}';
    }
}

    /**
     * 查询所有账户信息和当前账户所属用户信息
     * @return
     */
    List<Account> findAll();

重点:



 <mapper namespace="com.itheima.dao.IAccountDao">

    
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="aid">id>
        <result property="uid" column="uid">result>
        <result property="money" column="money">result>
        
        <association property="user" column="uid" javaType="User">
            <id property="id" column="id">id>
            <result property="username" column="username">result>
            <result property="address" column="address">result>
            <result property="sex" column="sex">result>
            <result property="birthday" column="birthday">result>
        association>
    resultMap>

    
    <select id="findAll" resultMap="accountUserMap">
        select u.*, a.id as aid, a.uid, a.money from account a, user u where u.id = a.uid
    select>
    
mapper>

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第4张图片

查询所有用户信息,同时获取到当前用户下所有账户信息(一对多的查询 )

主表实体包含从表实体的集合引用,User类中新增Account集合引用

package com.itheima.domain;

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

/**
 * 用户实体类
 */
public class User implements Serializable{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    // 一对多关系映射:主表实体包含从表实体的集合引用
    private List<Account> accounts;

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

    public void setAccounts(List<Account> accounts) {
        this.accounts = 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;
    }

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

IUserDao接口中:

    /**
     * 查询所有用户信息,同时获取到当前用户下所有账户信息
     * @return
     */
    List<User> findAll();

映射配置文件IUserDao.xml



 <mapper namespace="com.itheima.dao.IUserDao">

    
    <resultMap id="userAccount" type="User">
        <id property="id" column="id">id>
        <result property="username" column="username">result>
        <result property="birthday" column="birthday">result>
        <result property="sex" column="sex">result>
        <result property="address" column="address">result>
        
        <collection property="accounts" ofType="Account">
            <id property="id" column="aid">id>
            <result property="uid" column="uid">result>
            <result property="money" column="money">result>
        collection>
    resultMap>

    
    <select id="findAll" resultMap="userAccount">
        select * from user u left outer join account a on u.id=a.uid
    select>

mapper>

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第5张图片
测试类:

    /**
     * 测试查询所有
     */
    @Test
    public void findAll(){

        List<User> users = userDao.findAll();

        for (User user : users) {
            System.out.println("---------------------------");
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第6张图片

多对多查询

新建角色表role
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第7张图片
新建角色和用户的中间表role_user
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第8张图片
并且新建实体类Role,接口IRoleDao,映射配置文件IRoleDao.xml,测试类RoleTest
注意:Role的属性名和数据库属性名不同,User属性名和数据库中的属性名相同

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第9张图片
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第10张图片
项目结构:
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第11张图片

查询所有角色信息同时查询出该角色对应的所有用户信息

SQL语句:

SELECT u.*,r.`ID` AS rid, r.role_name,r.role_desc FROM role r
LEFT OUTER JOIN user_role ur ON r.id = ur.rid
LEFT OUTER JOIN USER u ON ur.uid = u.id;

sql语句查询结果
在这里插入图片描述
使用两次左外连接:
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第12张图片
IRoleDao接口中定义方法:

    /**
     * 查询所有角色,同时查询该角色的所有用户信息
     * @return
     */
    List<Role> findAll();

IRoleDao.xml中配置:



 <mapper namespace="com.itheima.dao.IRoleDao">

    
    <resultMap id="roleMap" type="Role">
        <id property="roleId" column="rid">id>
        <result property="roleName" column="role_name">result>
        <result property="roleDesc" column="role_desc">result>
        <collection property="users" ofType="User">
            <id property="id" column="id">id>
            <result property="username" column="username">result>
            <result property="birthday" column="birthday">result>
            <result property="sex" column="sex">result>
            <result property="address" column="address">result>
        collection>
    resultMap>

    
    <select id="findAll" resultMap="roleMap">
        SELECT u.*,r.`ID` AS rid, r.role_name,r.role_desc FROM role r
        LEFT OUTER JOIN user_role ur ON r.id = ur.rid
        LEFT OUTER JOIN USER u ON ur.uid = u.id;
    select>

mapper>

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第13张图片
测试类RoleTest中:

package com.itheima.test;

import com.itheima.dao.IRoleDao;
import com.itheima.domain.Role;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class RoleTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IRoleDao roleDao;

    @Before
    public void init() throws IOException {
        // 1.读取配置文件生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 3.获取SqlSession
        sqlSession = factory.openSession();
        // 4.生成代理对象
        roleDao = sqlSession.getMapper(IRoleDao.class);
    }

    @After
    public void destroy() throws IOException {
        // 释放资源
        sqlSession.close();
        in.close();
    }

    @Test
    public void testFindAll(){
        List<Role> roles = roleDao.findAll();
        for (Role role : roles) {
            System.out.println("--------------------------------");
            System.out.println(role);
            System.out.println(role.getUsers());
        }
    }

}

执行findAll方法:
2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第14张图片

查询所有用户信息同时查询出该用户对应的所有角色信息

依葫芦画瓢,先定义好sql语句

SELECT u.*,r.`ID` AS rid, r.role_name,r.role_desc FROM USER u
LEFT OUTER JOIN user_role ur ON u.id = ur.uid
LEFT OUTER JOIN role r ON ur.rid = r.id;

查询结果

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第15张图片
IUserDao接口中

    /**
     * 查询所有用户信息同时查询出该用户对应的所有角色信息
     * @return
     */
    List<User> findAll();

IUserDao.xml配置文件中



 <mapper namespace="com.itheima.dao.IUserDao">

    
    <resultMap id="userMap" type="User">
        <id property="id" column="id">id>
        <result property="username" column="username">result>
        <result property="birthday" column="birthday">result>
        <result property="sex" column="sex">result>
        <result property="address" column="address">result>
        <collection property="roles" ofType="Role">
            <id property="roleId" column="rid">id>
            <result property="roleName" column="role_name">result>
            <result property="roleDesc" column="role_desc">result>
        collection>
    resultMap>

    
    <select id="findAll" resultMap="userMap">
        SELECT u.*,r.`ID` AS rid, r.role_name,r.role_desc FROM USER u
        LEFT OUTER JOIN user_role ur ON u.id = ur.uid
        LEFT OUTER JOIN role r ON ur.rid = r.id;
    select>

mapper>

测试

    /**
     * 测试查询所有
     */
    @Test
    public void findAll(){

        List<User> users = userDao.findAll();

        for (User user : users) {
            System.out.println("---------------------------");
            System.out.println(user);
            System.out.println(user.getRoles());
        }
    }

2019/12/15 ~ 16:黑马Mybatis学习笔记(五)—— 多表查询_第16张图片

你可能感兴趣的:(Mybatis)