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等内容. 一.多表关联查询 表与 ...
随机推荐
- salesforce零基础学习(八十二)审批邮件获取最终审批人和审批意见
项目中,审批操作无处不在.配置审批流时,我们有时候会用到queue,related user设置当前步骤的审批人,审批人可以一个或者多个.当审批人有多个时,邮件中获取当前记录的审批人和审批意见就不能随 ...
- python密码错误三次锁定
程序需求: 输入用户名,密码 认证成功显示欢迎信息 输入错误三次后锁定用户 流程图: 好像画的不咋地 #!/usr/bin/env python # _*_ coding:utf-8 _*_ # Fi ...
- DIY 温控烙铁
由于工艺原因,某处要使用200W大功率烙铁(恒温烙铁虽然有那么大功率,但没有那么大的烙铁头),只能选用普通电热丝烙铁(无温控),存在温度过高现象(造成工艺不良,同时因助焊剂+高温造成烙铁头腐蚀),逐渐 ...
- 微信分享 JSSDK的使用
我现在做过的在微信中运行的项目,基本上都有微信分享功能,所以,会使用JSSDK分享页面是非常重要的.分享功能的代码一般会放在beforeCreate或mounted钩子中,代码如下: this.$ht ...
- [转载] Linux的Top命令解析
转载自http://www.jb51.net/LINUXjishu/34604.html.http://blog.csdn.net/hello_yang213/article/details/7455 ...
- flex词法解析
例子1.从标准输入的字数.单词.行数统计 %{ #include <string.h> int chars = 0; int lines = 0; int words = 0; %} %% ...
- 四、VueJs 填坑日记之搭建Axios接口请求工具
上一章,我们认识了项目的目录结构,以及对项目的目录结构做了一些调整,已经能把项目重新跑起来了.今天我们来搭建api接口调用工具Axios.Vue本身是不支持ajax调用的,如果你需要这些功能就需要安装 ...
- CTF 文件包含与伪协议
正巧在写代码审计的文章,无意间看到了一篇CTF的代码审计,CTF题目很好,用的姿势正如标题,文件包含和伪协议. 先放出原文链接(http://www.freebuf.com/column/150028 ...
- 方法的形参、ref参数、out参数的区别
我们在定义方法时,经常会涉及到传参.因为引用类型的数据在用变量存储时,是存储的地址,所以在传参时,依然是传递的地址,但是值类型的数据在传参时就会有所不同.值类型数据在调用方法传参时,普通情况下是值传递 ...
- canvas动画之动态绘出六边形
先上 demo: http://en.jsrun.net/W5iKp/show 这两天我一直在研究这个动画,花了大量的时间来想是如何实现的, 一开始我是想在进入 canvas 时按时间来用 lineT ...