JAVA入门[9]-mybatis多表关联查询
概要
本节要实现的是多表关联查询的简单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多表关联查询的更多相关文章
- 三、mybatis多表关联查询和分布查询
前言 mybatis多表关联查询和懒查询,这篇文章通过一对一和一对多的实例来展示多表查询.不过需要掌握数据输出的这方面的知识.之前整理过了mybatis入门案例和mybatis数据输出,多表查询是在前 ...
- mybatis多表关联查询之resultMap单个对象
resultMap的n+1方式实现多表查询(多对一) 实体类 创建班级类(Clazz)和学生类(Student),并在Student中添加一个Clazz类型的属性,用于表示学生的班级信息. mappe ...
- MyBatis 多表关联查询
多表关联查询 一对多 单条SQL实现. //根据部门编号查询出部门和部门成员姓名public dept selectAll() thorws Excatipon; //接口的抽象方法 下面是对应接口的 ...
- Mybatis多表关联查询字段值覆盖问题
一.错误展示 1.首先向大家展示多表关联查询的返回结果集 <resultMap id="specialdayAndWorktimeMap type="com.hierway. ...
- 5.mybatis一对一表关联查询
方式一:嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集,封装联表查询的数据(去除重复的数据) SELECT * FROM class c,teacher t WHERE c.tid = t.t ...
- spring boot 2使用Mybatis多表关联查询
模拟业务关系:一个用户user有对应的一个公司company,每个用户有多个账户account. spring boot 2的环境搭建见上文:spring boot 2整合mybatis 一.mysq ...
- 三、Mybatis多表关联查询应用
一对一查询 实现语句:select * from neworder o, user u where o.uid = u.id 实体Order: 接口: 配置: 测试: 一对多查询 实现语句:selec ...
- Spring Boot入门系列(十七)整合Mybatis,创建自定义mapper 实现多表关联查询!
之前讲了Springboot整合Mybatis,介绍了如何自动生成pojo实体类.mapper类和对应的mapper.xml 文件,并实现最基本的增删改查功能.mybatis 插件自动生成的mappe ...
- MyBatis学习总结(三)——多表关联查询与动态SQL
在上一章中我们学习了<MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射>,这一章主要是介绍一对一关联查询.一对多关联查询与动态SQL等内容. 一.多表关联查询 表与 ...
随机推荐
- 《Github入门与实践》读书笔记 蟲咋先生的追求之旅(上)
<Github入门与实践>作者: [日] 大塚弘记 译者:支鹏浩/刘斌 简介 本书从Git的基本知识和操作方法入手,详细介绍了GitHub的各种功能,GitHub与其他工具或服务的协作 ...
- 6. ZooKeeper访问控制列表
ZooKeeper的数据模型提供了ACL机制来控制访问znode. 在创建znode时,ACL将确定你可以在znode上执行的各种操作的权限. ZooKeeper ACL模型与Unix / Linux ...
- 常见sql注入原理详解!
1.首先我们创建一个mysqli的链接 /**数据库配置*/ $config = ['hostname'=>"localhost", 'port'=>"330 ...
- web-故道白云&Clound的错误
web-故道白云 题目: 解题思路: 0x01 首先看到题目说html里有秘密,就看了下源代码如图, 重点在红圈那里,表示输入的变量是id,当然上一行的method="get"同时 ...
- 《java.util.concurrent 包源码阅读》23 Fork/Join框架之Fork的冰山一角
上篇文章一直追踪到了ForkJoinWorkerThread的pushTask方法,仍然没有办法解释Fork的原理,那么不妨来看看ForkJoinWorkerThread的run方法: public ...
- 问题(一)---线程池,锁、堆栈和Hashmap相关
一.线程池: 多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力. 假设一个服务器完成一项任务所需时间为:T1 创建线程时间,T2 在线程中 ...
- 一些常用软件的静默安装参数(nsis,msi,InstallShield,Inno)
打包的时候,经常需要安装一些其它的环境库,而又不想让用户繁锁的去选择,这时就需要静默安装,而不同的文件所加的参数了不一致,比如VS的环境库vcredist_x86.exe(这是32位的环境库)后面加/ ...
- WPF开发的彩票程序(练手好例子) 附源码
前言 WPF是.NET最新的界面开发库,开发界面非常灵活!但是学习WPF难度也非常大. 应朋友之邀,编写了一个小程序.程序虽小,五脏俱全,WPF开发的灵活性可窥见一斑. 对于新手学习有很好的借鉴意义, ...
- Java数据结构和算法(三)——冒泡、选择、插入排序算法
上一篇博客我们实现的数组结构是无序的,也就是纯粹按照插入顺序进行排列,那么如何进行元素排序,本篇博客我们介绍几种简单的排序算法. 1.冒泡排序 这个名词的由来很好理解,一般河水中的冒泡,水底刚冒出来的 ...
- MFC中小笔记(三)
10.在添加新Menu之后,代码中 调用 创建的IDR_MENU1,一直出现 Debug Assertion Failed的情况.原因是,没有写入到 项目.RC中,需要更新下rc(资源文件). 然后进 ...