Mybatis多表關(guān)聯(lián)查詢的實現(xiàn)(DEMO)
概要
本節(jié)要實現(xiàn)的是多表關(guān)聯(lián)查詢的簡單demo。場景是根據(jù)id查詢某商品分類信息,并展示該分類下的商品列表。
一、Mysql測試數(shù)據(jù)
新建表Category(商品分類)和Product(商品),并插入幾條測試數(shù)據(jù)。
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核心技術(shù)');
二、配置mybatis-generator-config.xml
配置mybatis-generator-config.xml的方法見 JAVA入門[7]-Mybatis generator(MBG)自動生成mybatis代碼 ,這里主要改動的是table節(jié)點。
<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面板運(yùn)行mybatis-generator:generate,自動生成相關(guān)的類。
三、自定義mybatis關(guān)聯(lián)查詢
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節(jié)點,id對應(yīng)上面的方法名getById;parameterType參數(shù)類型為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節(jié)點id為CategoryResult,type為CategoryDto。
關(guān)于resultMap:
- id – 一個 ID 結(jié)果;標(biāo)記結(jié)果作為 ID 可以幫助提高整體效能
- result – 注入到字段或 JavaBean 屬性的普通結(jié)果
- association – 一個復(fù)雜的類型關(guān)聯(lián);許多結(jié)果將包成這種類型
- 嵌入結(jié)果映射 – 結(jié)果映射自身的關(guān)聯(lián),或者參考一個
- collection – 復(fù)雜類型的集
- 嵌入結(jié)果映射 – 結(jié)果映射自身的集,或者參考一個
完整參考官網(wǎng):http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
用association對應(yīng)category,collection對應(yīng)products,然后用result對應(yīng)到每個具體字段。
<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>
四、測試
在上一節(jié)測試基礎(chǔ)上新增測試方法:
@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()); } } }
運(yùn)行之后居然報錯了
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節(jié)點就可以了。
<resultMap id="CategoryResult" type="com.data.dto.CategoryDto"> <id property="id" column="CateId"></id> …… </resultMap>
運(yùn)行結(jié)果:
商品id=2 name=美妝
Products:6
|_膜法世家
|_御泥坊
|_雅詩蘭黛
|_歐萊雅
|_韓后
|_相宜本草
相關(guān)文章
Sonar編譯問題對應(yīng):File [...] can''t be indexed twice.
今天小編就為大家分享一篇關(guān)于Sonar編譯問題對應(yīng):File [...] can't be indexed twice.,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12Java Web應(yīng)用程序?qū)崿F(xiàn)基礎(chǔ)的文件下載功能的實例講解
這里我們演示了Servelet驅(qū)動Tomcat來進(jìn)行HTTP下載的方法,接下來就詳細(xì)來看Java Web應(yīng)用程序?qū)崿F(xiàn)基礎(chǔ)的文件下載功能的實例講解2016-05-05java使用java.util.Date獲取指定日期的年、月、日、時、分、秒
在Java中獲取當(dāng)前時間和日期是很常見的操作,也是很重要的操作,下面這篇文章主要給大家介紹了關(guān)于java使用java.util.Date獲取指定日期的年、月、日、時、分、秒的相關(guān)資料,需要的朋友可以參考下2024-01-01基于Java的打包jar、war、ear包的作用與區(qū)別詳解
本篇文章,小編為大家介紹,基于Java的打包jar、war、ear包的作用與區(qū)別詳解。需要的朋友參考下2013-04-04idea 無法創(chuàng)建Scala class 選項的原因分析及解決辦法匯總
這篇文章主要介紹了idea 無法創(chuàng)建Scala class 選項的解決辦法匯總,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09Java因項目配置不當(dāng)而引發(fā)的數(shù)據(jù)泄露
這篇文章主要介紹了Java因項目配置不當(dāng)而引發(fā)的數(shù)據(jù)泄露解決辦法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09