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用戶。
水平有限,文章如有錯誤,請各位大佬指出,避免誤人子弟。