SSM

MyBatis多表查询详解

Nick · 3月28日 · 2020年 · · · 本文9494字 · 阅读24分钟645

MyBatis多表查询

0. 分析

  1. 一对一
    一个用户只能拥有一个一个账户
    sql语句:
    select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id;
    MyBatis多表查询详解-左眼会陪右眼哭の博客
  2. 一对多
    一个用户可以拥有多个账户
    sql语句
    select u.*,a.id as aid ,a.uid,a.money from user u left outer join account
    a on u.id =a.uid
    MyBatis多表查询详解-左眼会陪右眼哭の博客
  3. 多对多
    一个用户可以有多个角色,一个角色可以有多个人
    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 u.id = ur.uid;
    MyBatis多表查询详解-左眼会陪右眼哭の博客

1. 建立数据库

1.user表
MyBatis多表查询详解-左眼会陪右眼哭の博客
2. account表
MyBatis多表查询详解-左眼会陪右眼哭の博客
3. role表
MyBatis多表查询详解-左眼会陪右眼哭の博客
4. 用户角色映射表 user_role
MyBatis多表查询详解-左眼会陪右眼哭の博客

2.配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.qkongtao</groupId>
    <artifactId>MyBatis_crud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>

3. mybatis的主配置文件 SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
        <mapper resource="dao/IUserDao.xml"/>
    </mappers>
    <!--起别名,可以不用谢写全限定类名-->
    <typeAliases>
        <typeAlias type="domain.User" alias="user"></typeAlias>
    </typeAliases>
</configuration>

4. 用到的javaBean封装类

  1. Account.java
package domain;/*
 *Created by tao on 2020-03-27.
 */

public class Account {
    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 +
                '}';
    }
}
  1. User.java
package domain;

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


public class User implements Serializable{

    private Integer id;
    private String name;
    private Date birthday;
    private String sex;
    private int age;
    private List<Account> accounts;


    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", accounts=" + accounts +
                '}';
    }
}
  1. Role.java
package domain;/*
 *Created by tao on 2020-03-27.
 */

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

public class Role implements Serializable {
    private Integer roleId;
    private String roleName;
    private String roleDesc;
    //多对多的关系映射:一个角色可以赋予多个用户
    private List<User> users;

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    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{" +
                "roleId=" + roleId +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                ", users=" + users +
                '}';
    }
}
  1. AccountUser.java
package domain;/*
 *Created by tao on 2020-03-27.
 */

import java.io.Serializable;

public class AccountUser extends Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;

    private User user;

    @Override
    public Integer getId() {
        return id;
    }

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

    @Override
    public Integer getUid() {
        return uid;
    }

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

    @Override
    public Double getMoney() {
        return money;
    }

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

    public User getUser() {
        return user;
    }

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

    @Override
    public String toString() {
        return "AccountUser{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                ", user=" + user +
                '}';
    }
}
  1. UserRole.java
package domain;/*
 *Created by tao on 2020-03-28.
 */

import java.util.List;

public class UserRole {
    private List<User> users;
    private List<Role> roles;

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

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

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    @Override
    public String toString() {
        return "UserRole{" +
                "users=" + users +
                ", roles=" + roles +
                '}';
    }
}

5. 用户的持久层接口 dao

IUserDao.java

<code class="language-clike line-numbers">package dao;

import domain.*;

import java.util.List;

/**
 * 用户的持久层接口
 */
public interface IUserDao {

    /**
     * 一对一查询
     * 查询所有账户,同时获取账户的所属用户名称以及它的个人信息
     *
     * @return
     */
    List<AccountUser> findAll();

    /**
     * 一对多查询
     *
     * @return
     */
    List<User> findAllDuo();

    /*
     * 多对多查询
     * */
    List<UserRole> findAllDDD();
}

6. 持久层 Dao 映射配置 IUserDao.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="dao.IUserDao">
    <!-- 配置 查询结果的列名和实体类的属性名的对应关系 -->

    <!--一对一:定义 AccountUser 表的 accountMap-->
    <resultMap id="accountMap" type="domain.AccountUser">
        <id column="aid" property="id"/>
        <result column="uid" property="uid"/>
        <result column="money" property="money"/>
        <!-- 它是用于指定从表方的引用实体属性的 -->
        <association property="user" javaType="domain.User">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <result column="sex" property="sex"/>
            <result column="birthday" property="birthday"/>
            <result column="age" property="age"/>
        </association>
    </resultMap>

    <!--一对多:定义 user 表的 userMap-->
    <resultMap id="userMap" type="domain.User">
        <!-- 主键字段的对应 -->
        <id property="id" column="id"></id>
        <!--非主键字段的对应-->
        <result property="name" column="name"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="age" column="age"></result>
        <!-- collection 是用于建立一对多中集合属性的对应关系ofType 用于指定集合元素的数据类型-->
        <collection property="accounts" ofType="domain.Account">
            <id column="aid" property="id"/>
            <result column="uid" property="uid"/>
            <result column="money" property="money"/>
        </collection>
    </resultMap>

    <!--多对多:定义 UserRole 表的 ResultMap-->
    <resultMap id="userRoleMap" type="domain.UserRole">
        <collection property="users" ofType="domain.User">
            <id column="id" property="id"></id>
            <result column="name" property="name"></result>
            <result column="age" property="age"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </collection>
        <collection property="roles" ofType="domain.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="accountMap">
        select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id;
    </select>

    <!--一对多查询所有-->
    <select id="findAllDuo" resultMap="userMap">
      select u.*,a.id as aid ,a.uid,a.money from user u left outer join account
       a on u.id =a.uid
    </select>

    <!--多对多查询-->
    <select id="findAllDDD" resultMap="userRoleMap">
       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 u.id = ur.uid;

    </select>

</mapper>

7. 测试类 MyBatisTest.java

<code class="language-clike line-numbers">package test;

import dao.IUserDao;
import domain.*;
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.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author tao
 * <p>
 * 测试mybatis的crud操作
 */
public class MybatisTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;

    @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();
        //4.获取dao的代理对象
        userDao = sqlSession.getMapper(IUserDao.class);
    }

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

    /**
     * 测试查询所有:一对一
     */
    @Test
    public void testFindAll1() {
        //执行查询所有方法
        List<AccountUser> accountUsers = userDao.findAll();
        for (AccountUser accountUser : accountUsers) {
            System.out.println(accountUser);
        }
    }

    /**
     * 测试查询所有:一对多
     */
    @Test
    public void testFindAll2() {
        List<User> users = userDao.findAllDuo();
        for (User user : users) {
            System.out.println("-------每个用户的内容---------");
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }


    /**
     * 测试查询所有:多对多
     */
    @Test
    public void testFindAll3() {
        List<UserRole> userRole = userDao.findAllDDD();
        for (UserRole role : userRole) {
            System.out.println(role);
        }

    }
}

结果如下

  1. 一对一
    MyBatis多表查询详解-左眼会陪右眼哭の博客
  2. 一对多
    MyBatis多表查询详解-左眼会陪右眼哭の博客
  3. 多对多
    MyBatis多表查询详解-左眼会陪右眼哭の博客
0 条回应
在线人数:1人 来访统计
隐藏