概要

本节要实现的是多表关联查询的简单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); 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://pan.baidu.com/s/1eScI7z8

JAVA入门[9]-mybatis多表关联查询的更多相关文章

  1. 三、mybatis多表关联查询和分布查询

    前言 mybatis多表关联查询和懒查询,这篇文章通过一对一和一对多的实例来展示多表查询.不过需要掌握数据输出的这方面的知识.之前整理过了mybatis入门案例和mybatis数据输出,多表查询是在前 ...

  2. mybatis多表关联查询之resultMap单个对象

    resultMap的n+1方式实现多表查询(多对一) 实体类 创建班级类(Clazz)和学生类(Student),并在Student中添加一个Clazz类型的属性,用于表示学生的班级信息. mappe ...

  3. MyBatis 多表关联查询

    多表关联查询 一对多 单条SQL实现. //根据部门编号查询出部门和部门成员姓名public dept selectAll() thorws Excatipon; //接口的抽象方法 下面是对应接口的 ...

  4. Mybatis多表关联查询字段值覆盖问题

    一.错误展示 1.首先向大家展示多表关联查询的返回结果集 <resultMap id="specialdayAndWorktimeMap type="com.hierway. ...

  5. 5.mybatis一对一表关联查询

    方式一:嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集,封装联表查询的数据(去除重复的数据)  SELECT * FROM class c,teacher t WHERE c.tid = t.t ...

  6. spring boot 2使用Mybatis多表关联查询

    模拟业务关系:一个用户user有对应的一个公司company,每个用户有多个账户account. spring boot 2的环境搭建见上文:spring boot 2整合mybatis 一.mysq ...

  7. 三、Mybatis多表关联查询应用

    一对一查询 实现语句:select * from neworder o, user u where o.uid = u.id 实体Order: 接口: 配置: 测试: 一对多查询 实现语句:selec ...

  8. Spring Boot入门系列(十七)整合Mybatis,创建自定义mapper 实现多表关联查询!

    之前讲了Springboot整合Mybatis,介绍了如何自动生成pojo实体类.mapper类和对应的mapper.xml 文件,并实现最基本的增删改查功能.mybatis 插件自动生成的mappe ...

  9. MyBatis学习总结(三)——多表关联查询与动态SQL

    在上一章中我们学习了<MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射>,这一章主要是介绍一对一关联查询.一对多关联查询与动态SQL等内容. 一.多表关联查询 表与 ...

随机推荐

  1. 使用duilib开发简单的Window安装包

    一.具体思路 安装过程:安装包的制作包括资源文件的打包,资源文件打包到安装包exe中,安装的时候需要从exe中提取出对应的资源文件, 然后解压文件安装到指定目录,然后就是对安装的可执行程序进行注册表的 ...

  2. [转载] Redis之七种武器

    转载自http://blog.nosqlfan.com/html/2942.html?ref=rediszt 长生剑.孔雀翎.碧玉刀.多情环.离别钩.霸王枪.拳头是古龙笔下的七种武器,而本文打算将Re ...

  3. java-基础-泛型

    java泛型通配符问题.   java中的泛型基本用法参考<java编程思想>第四版 p.353 java泛型中比较难理解的主要是类型擦除和通配符相关.   1.类型擦除 在编译期间,类型 ...

  4. riot.js教程【六】循环、HTML元素标签

    前文回顾 riot.js教程[五]标签嵌套.命名元素.事件.标签条件 riot.js教程[四]Mixins.HTML内嵌表达式 riot.js教程[三]访问DOM元素.使用jquery.mount输入 ...

  5. python坑之input获取字符串

    space = input("set user quotation:").strip() quotation = int(space* 1024 * 1024) print(quo ...

  6. PHP启动:动态库加载失败(PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/php7/lib/php/extensions/no-debug-non-zts-20151012/*.so')

    今天在linux上面智障一般搞了好久,本来想安装个swoole的,然后用  php -m 的命令想看下安装的PHP扩展库,发现有的扩展库有的可以出来,有的加载失败, 加载失败的错误类型: PHP Wa ...

  7. swaggerui在asp.net web api core 中的应用

    Swaggerui 可以为我们的webapi提供美观的在线文档,如下图: 实现步骤: NuGet Packages  Install-Package Swashbuckle.AspNetCore 在s ...

  8. 【魅族Pro7】——BootStrap/JQuery/Canvas/PHP/MySQL/Ajax爬坑之项目总结(一)

    前言:这个项目是我们小组团体合作完成的学习项目,项目使用魅族GUI设计和图片素材,响应式重构Pro7官网的首页.子页.商城及购物车,并加入一些创新.我主要负责的是[画屏子页]的项目,这里作为温故知新, ...

  9. 十五、Hadoop学习笔记————Zookeeper客户端的使用

    timeout表示会话超时时间,zookeeper靠与客户的心跳来判断会话是否有效(单位毫秒), -r为只读,表示zookeeper如果与半数以上服务器失去连接则会停止服务,如果有-r参数,则会继续保 ...

  10. 彻底理解线程同步与同步代码块synchronized

    public class Demo { public static synchronized void fun1(){ } public synchronized void fun2(){ } pub ...