Mybatis多表关联查询的实现(DEMO)
作者:陈敬(Cathy) 发布时间:2022-05-03 14:50:03
概要
本节要实现的是多表关联查询的简单demo。场景是根据id查询某商品分类信息,并展示该分类下的商品列表。
一、Mysql测试数据
新建表Category(商品分类)和Product(商品),并插入几条测试数据。
create table Category (
Id int not null auto_increment,
Name varchar(80) null,
constraint pk_category primary key (Id)
);
INSERT INTO category(Name) VALUES ('女装');
INSERT INTO category(Name) VALUES ('美妆');
INSERT INTO category(Name) VALUES ('书籍');
create table product (
Id int not null auto_increment,
categoryId int not null,
Name varchar(80) null,
constraint pk_product primary key (Id),
constraint fk_product_2 foreign key (categoryId)
references category (Id)
);
create index productCat on product (categoryId);
create index productName on product (Name);
INSERT INTO product(CategoryId,Name) VALUES (1, '裂帛');
INSERT INTO product(CategoryId,Name) VALUES (1, '雅鹿');
INSERT INTO product(CategoryId,Name) VALUES (2,'膜法世家');
INSERT INTO product(CategoryId,Name) VALUES (2,'御泥坊');
INSERT INTO product(CategoryId,Name) VALUES (2, '雅诗兰黛');
INSERT INTO product(CategoryId,Name) VALUES (2, '欧莱雅');
INSERT INTO product(CategoryId,Name) VALUES (2, '韩后');
INSERT INTO product(CategoryId,Name) VALUES (2, '相宜本草');
INSERT INTO product(CategoryId,Name) VALUES (3,'疯狂JAVA');
INSERT INTO product(CategoryId,Name) VALUES (3,'JAVA核心技术');
二、配置mybatis-generator-config.xml
配置mybatis-generator-config.xml的方法见 JAVA入门[7]-Mybatis generator(MBG)自动生成mybatis代码 ,这里主要改动的是table节点。
<table tableName="category" enableCountByExample="true" enableDeleteByExample="true" enableSelectByExample="true" enableUpdateByExample="true">
<generatedKey column="Id" sqlStatement="mysql" identity="true"/>
</table>
<table tableName="product" enableCountByExample="true" enableSelectByExample="true" enableSelectByPrimaryKey="true" enableUpdateByPrimaryKey="true" enableDeleteByPrimaryKey="true" enableInsert="true">
<generatedKey column="Id" sqlStatement="mysql" identity="true"></generatedKey>
</table>
配置好xml文件后,在Maven面板运行mybatis-generator:generate,自动生成相关的类。
三、自定义mybatis关联查询
1.封装实体dto
我们新定义CategoryDto,封装商品分类信息及其商品列表。
public class CategoryDto {
private Category category;
private List<Product> products;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
2.为CategoryMapper.java接口新增方法getById()
CategoryDto getById(int id);
3.配置CategoryMapper.xml
首先定义select节点,id对应上面的方法名getById;parameterType参数类型为Integer;resultMap为自定义resultMap的id。
<select id="getById" parameterType="java.lang.Integer" resultMap="CategoryResult">
SELECT Category.Id AS CateId,Category.Name AS CateName,Product.Id AS ProductId,Product.Name AS ProductName
FROM Category,Product
WHERE Category.Id=Product.CategoryId AND Category.Id=#{id}
</select>
接下来定义resultMap节点id为CategoryResult,type为CategoryDto。
关于resultMap:
id – 一个 ID 结果;标记结果作为 ID 可以帮助提高整体效能
result – 注入到字段或 JavaBean 属性的普通结果
association – 一个复杂的类型关联;许多结果将包成这种类型
嵌入结果映射 – 结果映射自身的关联,或者参考一个
collection – 复杂类型的集
嵌入结果映射 – 结果映射自身的集,或者参考一个
完整参考官网:http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
用association对应category,collection对应products,然后用result对应到每个具体字段。
<resultMap id="CategoryResult" type="com.data.dto.CategoryDto">
<association property="category" javaType="com.data.pojo.Category">
<result property="id" column="CateId"></result>
<result property="name" column="CateName"></result>
</association>
<collection property="products" ofType="com.data.pojo.Product">
<result property="id" column="ProductId"></result>
<result property="name" column="ProductName"></result>
</collection>
</resultMap>
四、测试
在上一节测试基础上新增测试方法:
@Test
public void test_getById(){
int id=2;
CategoryDto dto= categoryMapper.getById(id);
if(dto==null){
System.out.println("不存在");
}else {
System.out.println("商品id="+dto.getId()+" name="+dto.getCategory().getName());
System.out.println("Products:"+dto.getProducts().size());
for(Product product:dto.getProducts()){
System.out.println(" |_"+product.getName());
}
}
}
运行之后居然报错了
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 6
后来找到了解决方案,修改resultMap,添加id节点就可以了。
<resultMap id="CategoryResult" type="com.data.dto.CategoryDto">
<id property="id" column="CateId"></id>
……
</resultMap>
运行结果:
商品id=2 name=美妆
Products:6
|_膜法世家
|_御泥坊
|_雅诗兰黛
|_欧莱雅
|_韩后
|_相宜本草
来源:http://www.cnblogs.com/janes/archive/2017/02/24/6437351.html
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 前言smart-doc 是一款同时支持 java restful api 和 Apache Dubbo rpc 接口文档生成的工具,smar
- 本文实例为大家分享了Java实现简单员工管理系统的具体代码,供大家参考,具体内容如下代码如下:import java.util.*;publ
- Java中字符串对象创建有两种形式,一种为字面量形式,如String str = "hello";,另一种就是使用new
- 在定位JVM性能问题时可能会遇到内存泄露导致JVM OutOfMemory的情况,在使用Tomcat容器时如果设置了reloadable=”
- java常量池是一个经久不衰的话题,也是面试官的最爱,题目花样百出,这次好好总结一下。理论先拙劣的表达一下jvm虚拟内存分布:程序计数器是j
- 本文主要介绍了java中LinkedList使用迭代器优化移除批量元素原理,分享给大家,具体如下:public interface Iter
- 在项目迁移到Spring Boot之后,发生内存使用量过高的问题。本文介绍了整个排查过程以及使用到的工具,也非常适用于其他堆外内存排查。背景
- 目录操作创建目录File类中有两个方法可以用来创建文件夹:mkdir( )方法创建一个文件夹,成功则返回true,失败则返回false。失败
- 相关知识:Java中三种简单注解介绍和代码实例一、作用用 @Deprecated注解的程序元素,不鼓励程序员使用这样的元素,通常是因为它很危
- 目录Sonar概述一、 搭建sona服务二、idea配置三、 配置maven的setting.xml文件四、idea中 mvn sonar:
- 方式一public class Test{ public static void main(String[] args) throws Ex
- 知识点:1.使用SQL Helper创建数据库2.数据的增删查改(PRDU:Put、Read、Delete、Update)背景知识:上篇文章
- 按行读取文件package test; import java.io.*; import java.util.*; public class
- 问题背景通常我们开发的时候,需要联合控制台和Navicat/PLSQL等工具进行语句的拼接检查,如果只是输出了一堆???,那么将极大降低我们
- Filter简介Filter也称之为过滤器,它是Servlet技术中最实用的技术,WEB开发人员通过Filter技术,对web服务器管理的所
- 什么是Spring BatchSpring Batch 是一个轻量级的、完善的批处理框架,旨在帮助企业建立健壮、高效的批处理应用。Sprin
- 一. 为什么要使用接口假如有一个需求:要求实现防盗门的功能。门有"开"和"关"的功能,锁有"
- 1.依赖的jar文件 jsch-0.1.53.jar2.登录方式有密码登录,和密匙登录 代码:主函数:import java.ut
- 场景女朋友最近被安排了一个企业微信添加客户的沙雕活,然后跟我吐槽说,每天都要加,都想离职了,为了不让女朋友那么难受,突然想到可以使用Robo
- 效果展示在实际项目当中我们经常看到如下各种剪裁形状的效果,Flutter 为我们提供了非常方便的 Widget 很轻松就可以实现,下面我们来