MyBatis的关联查询!!!(一对一、一对多、多对多)

准备工作:

        1.创建Maven工程,还没有配置Maven的和还不会的去看这里啦:maven的下载安装与配置环境变量!!!(全网最详细)-CSDN博客

Account.java :     (pojo类)     (这里我们说明一下,根据我们下边的需求,我们需要将两张表查询出来的数据存到Account中,所以我们在Account这个实体类中添加了一个User的属性)

package com.by.pojo;

import java.io.Serializable;

public class Account implements Serializable {

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

    private User user;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                ", 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;
    }
}

 User.java:

/*
 * Copyright (c) 2020, 2023,  All rights reserved.
 *
 */
package com.by.pojo;

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

/**
 * 

Project: mybatis - User

*

Powered by scl On 2023-12-18 11:38:09

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public class User implements Serializable { private Integer id; private String username; private Date birthday; private String sex; private String address; 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 + '\'' + '}'; } }

     2.导入依赖到pom.xml文件中

 
                
                org.mybatis
                mybatis
                3.4.5
                
                
                    mysql
                    mysql-connector-java
                    5.1.47
                
                
                    log4j
                    log4j
                    1.2.17
                
                
                    junit
                    junit
                    4.12
                
            
            
                
                
                    
                        src/main/java
                        
                            **/*.xml
                        
                    
                    
                        src/main/resources
                    
                
            

    3.在resources中创建log4j.properites和mybatis-config.xml

log4j.properites:

    log4j.properites:
     
        # Global logging configuration
        log4j.rootLogger=DEBUG, stdout
        # Console output...
        log4j.appender.stdout=org.apache.log4j.ConsoleAppender
        log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
        log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

 mybatis-config.xml:

   
        
        
            
            
                
                
                    
                    
                    
                        
                        
                        
                        
                    
                
            
            
            
                
            
        

    4.创建RolerMapper接口和RoleMapper.xml文件

AccountMapper.java:

package com.by.mapper;

import com.by.pojo.Account;

import java.util.List;


public interface AccountMapper {
   
}

AccountMapper.xml:





    5.创建测试类MyBatisTest


         /*
     * Copyright (c) 2020, 2023,  All rights reserved.
     *
     */
    package com.by;
     
    import com.by.mapper.RoleMapper;
    import com.by.pojo.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 MyBatisTestRole {
     
        private InputStream inputStream;
        private SqlSession sqlSession;
     
        @Before
        public void init() throws IOException {
            // 加载配置文件
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
     
            // 创建sqlSessionFActory
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
     
            // 获得数据的绘画实例
            sqlSession = sessionFactory.openSession();
        }
     
     
        @After
        public void close() throws IOException {
            inputStream.close();
            sqlSession.close();
        }
     
    }

6.数据库文件

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50732
Source Host           : localhost:3306
Source Database       : mybatis

Target Server Type    : MYSQL
Target Server Version : 50732
File Encoding         : 65001

Date: 2021-12-24 11:51:18
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('1', '41', '1000');
INSERT INTO `account` VALUES ('2', '45', '1000');
INSERT INTO `account` VALUES ('3', '41', '2000');

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `ID` int(11) NOT NULL COMMENT '编号',
  `ROLE_NAME` varchar(30) DEFAULT NULL COMMENT '角色名称',
  `ROLE_DESC` varchar(60) DEFAULT NULL COMMENT '角色描述',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', '院长', '管理整个学院');
INSERT INTO `role` VALUES ('2', '总裁', '管理整个公司');
INSERT INTO `role` VALUES ('3', '校长', '管理整个学校');

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

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('41', '张三丰', '111', '2018-02-27 17:47:08', '男', '上海徐汇');
INSERT INTO `user` VALUES ('42', '宋远桥', '111', '2018-03-02 15:09:37', '女', '北京昌平');
INSERT INTO `user` VALUES ('43', '俞莲舟', '111', '2018-03-04 11:34:34', '女', '陕西西安');
INSERT INTO `user` VALUES ('45', '张翠山', '111', '2018-03-04 12:04:06', '男', '山东济南');
INSERT INTO `user` VALUES ('46', '殷梨亭', '111', '2018-03-07 17:37:26', '男', '河北张家口');
INSERT INTO `user` VALUES ('48', '莫声谷', '111', '2018-03-08 11:44:00', '女', '山西太原');

-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) DEFAULT NULL,
  `rid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '45', '1');
INSERT INTO `user_role` VALUES ('2', '41', '1');
INSERT INTO `user_role` VALUES ('3', '45', '2');

  准备工作完成后,开始功能的开发:

1.一对一的关联查询

MyBatis的关联查询!!!(一对一、一对多、多对多)_第1张图片

需求:现在有两张表,根据account表中的uid和user表中的id,将这两张表结合起来查询,并返回数据。

根据需求我们,开始开发:

(1)AccountMapper.java中添加一个方法:


    Account findAll(Integer id);

(2)在AccountMapper.xml文件中映射相应的方法:


    
        
        
        

        
            
            
            
            
            
        
    
    

(3)测试类:添加这个方法


    @Test
    public void findAccountById(){
        AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
        Account account = accountMapper.findAll(2);
        System.out.println(account);
    }

(4)结果展示:

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

2.一对多关联查询(一个用户可以有多个账户)

(1)首先应该在User Mapper.java文件中添加一个方法。

package com.by.mapper;

import com.by.pojo.User;

import java.util.List;

/**
 * 

Project: mybatis - UserMapper

*

Powered by scl On 2023-12-22 15:52:05

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public interface UserMapper { /** * 一对多 */ List findAllUserAccount(Integer id); }

(2)在UserMapper.xml文件在实现这个方法。




    
        
        
        
        
        


        
            
            
            
        
    
    

(3)在User实体类中添加List accountList;并重写toString方法。


    private List accountList;

    public List getAccountList() {
        return accountList;
    }

    public void setAccountList(List accountList) {
        this.accountList = accountList;
    }

(4)编写测试类:

/*
 * Copyright (c) 2020, 2023,  All rights reserved.
 *
 */
package com.by;

import com.by.mapper.AccountMapper;
import com.by.mapper.RoleMapper;
import com.by.mapper.UserMapper;
import com.by.pojo.Role;
import com.by.pojo.User;
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;


/**
 * 

Project: mybatis - MyBatisTest

*

Powered by scl On 2023-12-18 11:44:53

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public class MyBatisTestRole { private InputStream inputStream; private SqlSession sqlSession; @Before public void init() throws IOException { // 加载配置文件 String resource = "mybatis-config.xml"; inputStream = Resources.getResourceAsStream(resource); // 创建sqlSessionFActory SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 获得数据的绘画实例 sqlSession = sessionFactory.openSession(); } /** * 一对多,查询一个用户名下有几张卡 */ @Test public void findAllUserAccount() { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List allUserAccount = userMapper.findAllUserAccount(41); for (User user : allUserAccount) { System.out.println(user); } } @After public void close() throws IOException { inputStream.close(); sqlSession.close(); } }

(5)结果展示:

MyBatis的关联查询!!!(一对一、一对多、多对多)_第3张图片

3.多对多关联查询(查询角色及角色赋予的用户信息 )

(1)RoleMapper接口中定义一个方法:

package com.by.mapper;

import com.by.pojo.Role;
import com.by.pojo.User;

import java.util.List;

/**
 * 

Project: mybatis - RoleMapper

*

Powered by scl On 2023-12-20 14:37:16

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public interface RoleMapper { List findAllRoleByUser(Integer id); }

(2)在RoleMapper.xml文件中实现这个方法。




    
        
        
        
        
            
            
            
            
            
        
    

    

(3)实体类Role:

/*
 * Copyright (c) 2020, 2023,  All rights reserved.
 *
 */
package com.by.pojo;

import java.util.List;

/**
 * 

Project: mybatis - Role

*

Powered by scl On 2023-12-20 14:36:04

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public class Role { private int id; private String roleName; private String roleDesc; private List userList; public List getUserList() { return userList; } public void setUserList(List userList) { this.userList = userList; } @Override public String toString() { return "Role{" + "id=" + id + ", roleName='" + roleName + '\'' + ", roleDesc='" + roleDesc + '\'' + ", userList=" + userList + '}'; } public int getId() { return id; } public void setId(int 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; } }

(4)测试类:

/*
 * Copyright (c) 2020, 2023,  All rights reserved.
 *
 */
package com.by;

import com.by.mapper.AccountMapper;
import com.by.mapper.RoleMapper;
import com.by.mapper.UserMapper;
import com.by.pojo.Role;
import com.by.pojo.User;
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;


/**
 * 

Project: mybatis - MyBatisTest

*

Powered by scl On 2023-12-18 11:44:53

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public class MyBatisTestRole { private InputStream inputStream; private SqlSession sqlSession; @Before public void init() throws IOException { // 加载配置文件 String resource = "mybatis-config.xml"; inputStream = Resources.getResourceAsStream(resource); // 创建sqlSessionFActory SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 获得数据的绘画实例 sqlSession = sessionFactory.openSession(); } /** * 多对多:一个人对应多个身份,一个身份包含不同的人 * * @throws IOException */ @Test public void findAllRoleByUser() { RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); List allRoleByUser = roleMapper.findAllRoleByUser(45); for (Role role : allRoleByUser) { System.out.println(role); } } @After public void close() throws IOException { inputStream.close(); sqlSession.close(); } }

(5)结果展示:

MyBatis的关联查询!!!(一对一、一对多、多对多)_第4张图片

你可能感兴趣的:(mybatis,单元测试)