欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis多表连接

程序员文章站 2022-07-12 13:50:50
...

Mybatis多表连接

    此博文主要是记录自己日常学习以及讲述给学弟的随堂笔记,故你可能会看不到完整的代码,考虑到你也兴趣,
    文章末尾会附上本文完整的业务需求代码素材,建议你先看末尾,再来看前文。
    转载请附上原文链接。             
                                                                   河南济源普普通通的追梦孩
                                                                           ——爱猫狗的小郝
                                                                             2020/05/06

前言

两种类型

resultType和resultMap都可以完成输出映射:

  • resultType映射要求sql查询的列名和输出映射pojo类型的属性名一致(不一致可以通过起别名来解决)
  • resultMap映射时对sql查询的列名和输出映射pojo类型的属性名作一个对应关系。(不一致也无所谓)
resultType :直接表示返回类型
基本数据类型
复杂数据类型
resultMap :对外部resultMap的引用
应用场景:
数据库字段信息与对象属性不一致
复杂的联合查询,*控制映射结果
二者不能同时存在,本质上都是Map数据结构

resultMap

解决列名与实体类属性名不一致的问题,同时解决多表连接的查询问题。

操作步骤
  • 分析需求(主查询表、关联查询表)
  • 编写sql语句
  • resultMap进行映射的思路,在相应的pojo里加关联
  • 编写NewsMapper.xml
  • 编写NewsMapperr.java
  • 单元测试
  • 前端界面展示

resultMap映射问题

resultMap的配置

 <resultMap id="newsResultMap" type="hsy.cool.bean.News">
        <result property="id" column="id"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
        <result property="users_id" column="users_id"/>
        <result property="category_id" column="category_id"/>
        <result property="pubtime" column="pubtime"/>
        <result property="keywords" column="keywords"/>
        <result property="state" column="state"/>
        <result property="check_users_id" column="check_users_id"/>
        <result property="check_time" column="check_time"/>
        <result property="is_elite" column="is_elite"/>
    </resultMap>

查询

 <select id="findAllNor" resultMap="newsResultMap">
       select * from n_news
    </select>

java代码

 List<News>findAllNor();

单元测试

@Test
    public void findAllNor(){
        NewsMapper dao= MybatisUtils.getMapper(NewsMapper.class);
        List<News> list=dao.findAllNor();
        Assert.assertNotNull(list);
        Assert.assertEquals(8,list.size());
        String time= DateUtils.parse(list.get(0).getCheck_time());
        Assert.assertEquals("2020-04-10 11:41:40",time);
    }

多表连接——简单

通过增加简单类型的属性实现展⽰多表数据的⽬的

resultMap新增

 <result property="usersName" column="nickname"/>
 <result property="categoryName" column="name"/>
 <result property="checkUsersName" column="nickname"/>

实体类新增属性

    private String usersName;
    private String categoryName;
    private String checkUsersName;
    // setter/getter

单元测试新增

 Assert.assertEquals("匿名",list.get(0).getUsersName());

多表连接——复杂

通过在实体类中添加对象的类型的属性以及assocation标签实现对复杂数据类型的映射

    <resultMap id="newsMapComplex" type="hsy.cool.bean.News">
        <result property="id" column="id"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
        <result property="users_id" column="users_id"/>
        <result property="category_id" column="category_id"/>
        <result property="pubtime" column="pubtime"/>
        <result property="keywords" column="keywords"/>
        <result property="state" column="state"/>
        <result property="check_users_id" column="check_users_id"/>
        <result property="check_time" column="check_time"/>
        <result property="is_elite" column="is_elite"/>
        <result property="categoryName" column="name"/>
        <result property="checkUsersName" column="nickname"/>
        <association property="own" javaType="hsy.cool.bean.Users">
            <result property="id" column="id"/>
            <result property="nickname" column="nickname"/>
            <result property="realname" column="realname"/>
            <result property="phone" column="phone"/>
            <result property="email" column="email"/>
            <result property="address" column="address"/>
            <result property="createTime" column="create_time"/>
        </association>
    </resultMap>

查询

 <select id="findAllComplex" resultMap="newsMapComplex">
       select
         n.id,
         title,
         content,
         users_id,
         category_id,
         c.name,
         pubtime,
         keywords,
         state,
         check_users_id,
         u1.nickname,
         check_time,
         is_elite,
         u.*
        from n_news n inner join n_users u on n.users_id=u.id
                       inner join n_category c on n.category_id=c.id
                       inner join n_users u1 on n.check_users_id=u1.id
    </select>

java代码

  List<News>findAllComplex();

实体类新增

  private Users own;
  //setter/getter

单元测试

    @Test
    public void  findAllComplex(){
        NewsMapper dao=MybatisUtils.getMapper(NewsMapper.class);
        List<News> list=dao.findAllComplex();
        Assert.assertNotNull(list);
        Assert.assertEquals(8,list.size());
        String time= DateUtils.parse(list.get(0).getCheck_time());
        Assert.assertEquals("2020-04-10 11:41:40",time);
        Assert.assertEquals("匿名啊啊啊",list.get(0).getOwn().getNickname());
    }

JSP页面修改

          <td class="users">${news.own.nickname}
              <div class="usersInfo">
                  <table>
                      <tr>
                          <td>账号:</td>
                          <td>${news.own.nickname}</td>
                      </tr>

                      <tr>
                          <td>姓名:</td>
                          <td>${news.own.realname}</td>
                      </tr>

                      <tr>
                          <td>电话:</td>
                          <td>${news.own.phone}</td>
                      </tr>

                      <tr>
                          <td>邮件:</td>
                          <td>${news.own.email}</td>
                      </tr>

                      <tr>
                          <td>地址:</td>
                          <td>${news.own.address}</td>
                      </tr>
                  </table>
              </div>
          </td>

java代码修改

List<News> list=newsDao.findAllComplex();

添加样式

    <style type="text/css">
        .usersInfo{
            width: 200px;
            background: #eee;
        }
    </style>

样式修改

    <style type="text/css">
        .usersInfo{
            width: 200px;
            background: #eee;
            position: absolute;
            display: none;
        }
    </style>

导入jquery

    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js">
    </script>

动态样式

    <script>
        //选择器.动作
        $(function(){
            $(".users").hover(function(){
                $(".usersInfo",this).css("display","block");
            },function(){
                $(".usersInfo",this).css("display","none");
            });
        });
    </script>

完整页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>新闻列表</title>
    <style type="text/css">
        .usersInfo{
            width: 200px;
            background: #eee;
            position: absolute;
            display: none;
        }
    </style>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
    <script>

        $(function(){
            $(".users").hover(function(){
                $(".usersInfo",this).css("display","block");
            },function(){
                $(".usersInfo",this).css("display","none");
            });
        });
    </script>
</head>
<body>
<p>首页/新闻</p>
<h1>新闻列表</h1>
  <table width="1000" border="1">
      <tr>
          <th>编号</th>
          <th>标题</th>
          <th>内容</th>
          <th>分类</th>
          <th>作者</th>
          <th>关键字</th>
          <th>发布时间</th>
          <th>审批</th>
      </tr>
      <c:forEach items="${list}" var="news">
      <tr>
          <td>${news.id}</td>
          <td>${news.title}</td>
          <td>${news.content}</td>
          <td>${news.categoryName}</td>
          <td class="users">${news.own.nickname}
              <div class="usersInfo">
                  <table>
                      <tr>
                          <td>账号:</td>
                          <td>${news.own.nickname}</td>
                      </tr>

                      <tr>
                          <td>姓名:</td>
                          <td>${news.own.realname}</td>
                      </tr>

                      <tr>
                          <td>电话:</td>
                          <td>${news.own.phone}</td>
                      </tr>

                      <tr>
                          <td>邮件:</td>
                          <td>${news.own.email}</td>
                      </tr>

                      <tr>
                          <td>地址:</td>
                          <td>${news.own.address}</td>
                      </tr>
                  </table>
              </div>
          </td>
          <td>${news.keywords}</td>
          <td>${news.pubtimeString}</td>
          <td>${news.checkUsersName}</td>
      </tr>
      </c:forEach>

  </table>
</body>
</html>

业务素材

数据库表

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80016
 Source Host           : localhost:3306
 Source Schema         : news

 Target Server Type    : MySQL
 Target Server Version : 80016
 File Encoding         : 65001

 Date: 21/02/2020 16:56:04
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for n_access_logs
-- ----------------------------
DROP TABLE IF EXISTS `n_access_logs`;
CREATE TABLE `n_access_logs`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `intime` datetime(0) DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),
  `news_id` int(11) DEFAULT NULL,
  `users_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for n_category
-- ----------------------------
DROP TABLE IF EXISTS `n_category`;
CREATE TABLE `n_category`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of n_category
-- ----------------------------
INSERT INTO `n_category` VALUES (1, '时事');
INSERT INTO `n_category` VALUES (2, '财经');
INSERT INTO `n_category` VALUES (3, '体育');
INSERT INTO `n_category` VALUES (4, '娱乐');
INSERT INTO `n_category` VALUES (5, '科技');
INSERT INTO `n_category` VALUES (6, '旅游');

-- ----------------------------
-- Table structure for n_news
-- ----------------------------
DROP TABLE IF EXISTS `n_news`;
CREATE TABLE `n_news`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `content` text CHARACTER SET utf8 COLLATE utf8_bin,
  `users_id` int(11) DEFAULT NULL,
  `category_id` int(11) DEFAULT NULL,
  `pubtime` datetime(0) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
  `keywords` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `state` int(11) DEFAULT NULL COMMENT '1=新建,2=审批,3=删除',
  `check_users_id` int(11) DEFAULT NULL,
  `check_time` datetime(0) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
  `is_elite` int(11) DEFAULT NULL COMMENT '1=精华,0=非精华',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for n_replys
-- ----------------------------
DROP TABLE IF EXISTS `n_replys`;
CREATE TABLE `n_replys`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `news_id` int(11) DEFAULT NULL,
  `content` varchar(1024) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `users_id` int(11) DEFAULT NULL,
  `replys_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for n_short_replys
-- ----------------------------
DROP TABLE IF EXISTS `n_short_replys`;
CREATE TABLE `n_short_replys`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `news_id` int(11) DEFAULT NULL,
  `type` int(11) DEFAULT NULL COMMENT '1=赞,0=踩',
  `create_time` datetime(0) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
  `users_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for n_users
-- ----------------------------
DROP TABLE IF EXISTS `n_users`;
CREATE TABLE `n_users`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `realname` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `pwd` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `email` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `create_time` datetime(0) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
  `type` int(11) DEFAULT NULL COMMENT '0=管理员,1=读者,2=编辑',
  `realid` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '身份证号',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of n_users
-- ----------------------------
INSERT INTO `n_users` VALUES (1, '管理员', NULL, '123', NULL, NULL, NULL, '2019-10-09 10:06:39', 0, NULL);
INSERT INTO `n_users` VALUES (2, '匿名', NULL, '123', NULL, NULL, NULL, '2019-10-09 10:11:42', 1, NULL);

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 23 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '张三', '110');
INSERT INTO `student` VALUES (2, '李四', '120');
INSERT INTO `student` VALUES (3, '王五', '119');
INSERT INTO `student` VALUES (4, '赵六', '110');
INSERT INTO `student` VALUES (15, 'xxx', '111');
INSERT INTO `student` VALUES (16, 'xxx', '111');
INSERT INTO `student` VALUES (17, 'xxx', '111');
INSERT INTO `student` VALUES (18, 'xxx', '111');
INSERT INTO `student` VALUES (19, 'xxx', '111');
INSERT INTO `student` VALUES (20, 'xxx', '111');
INSERT INTO `student` VALUES (21, 'xxx', '111');

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `pwd` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `phone` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `email` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (1, '张三', '123', '110', '[email protected]', '洛阳');
INSERT INTO `users` VALUES (2, '李四', '111', '110', '[email protected]', '洛阳');
INSERT INTO `users` VALUES (3, '李四', '555', '110', '[email protected]', '洛阳');

SET FOREIGN_KEY_CHECKS = 1;

其它素材可以看我同系列博文,如有兴趣,请加群870299801,备注:CSDN用户。

水平有限,文章如有错误,请各位大佬指出,避免误人子弟。

完整版请看https://haosy.blog.csdn.net/article/details/105958872

相关标签: MyBatis 实验室