首頁  >  文章  >  Java  >  MyBatis關聯查詢的實例教程

MyBatis關聯查詢的實例教程

零下一度
零下一度原創
2017-06-25 10:34:331555瀏覽

轉載請註明出處:

前面有將到:Spring+SpringMVC+MyBatis深入學習及搭建(五)——動態sql

#1.商品訂單資料模型

1.1資料模型分析想法

(1)每張表記錄的資料內容

  分模組對每張表記錄的內容進行熟悉,相當於你學習系統需求(功能)的過程。

(2)每張表格重要的欄位設定

  非空白欄位、外鍵欄位

(3)資料庫層級表與表格之間的關係

  外鍵關係

(4)表與表之間的業務關係

  在分析表與表之間的業務關係時,一定要建立在某個業務意義基礎上去分析。

1.2屬性模型分析

2.一對一查詢

2.1需求

查詢訂單信息,關聯查詢下單用戶資訊。

2.2方法一:resultType

2.2.1sql語句

確定查詢的主表:訂單表

確定查詢的關聯表:使用者表

  關聯查詢使用內連結?還是外鏈結?

  由於orders表中有一個外鍵(user_id),透過外鍵關聯查詢使用者表只能查詢出一筆記錄,可使用內連結。

SELECT 
  orders.*,  USER.username,  USER.sex,  USER.address 
FROM
  orders,  USER WHERE orders.user_id = user.id

2.2.2建立pojo

 將上邊sql查詢的結果對應到pojo中,pojo中必須包含所有查詢列名。

原始Orders.java無法對應全部字段,需要新建立pojo。

建立一個pojo繼承包含查詢欄位較多的pojo類別。

2.2.3mapper.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离
    注意:使用mapper代理开发时,namespace有特殊作用,namespace等于mapper接口地址  --><mapper namespace="joanna.yan.mybatis.mapper.OrdersCustomMapper"><!--查询订单,关联查询用户信息  --><select id="findOrdersUser" resultType="joanna.yan.mybatis.entity.OrdersCustom">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address 
        FROM
          orders,
          USER 
        WHERE orders.user_id = user.id</select></mapper>

2.2.4mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息public List<OrdersCustom> findOrdersUser() throws Exception;
}

2.2.5測試程式

  @Testpublic void findOrdersUserTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<OrdersCustom> list=ordersCustomMapper.findOrdersUser();
        System.out.println(list);
        sqlSession.close();
    }

2.3方法二:resultMap

2.3.1sql語句

同resultType實作的sql

2.3.2使用resultMap映射的想法

使用resultMap將查詢結果中的訂單資訊對應到Orders物件中,在Orders類別中新增User屬性,將關聯查詢出來的使用者資訊映射到orders物件中的user屬性。

2.3.3需要orders類別中新增user屬性

2.3.4mapper.xml

2.3.4.1定義resultMap

#
    <!--订单关联查询用户的resultMap
        将整个查询的结果映射到oanna.yan.mybatis.entity.Orders中      --><resultMap type="joanna.yan.mybatis.entity.Orders" id="OrdersUserResultMap"><!-- 1.配置映射的订单信息  --><!-- id:指定查询列中的唯一标识,订单信息中的唯一标识,如果有多个列组成唯一标识,配置多个id
             column:订单信息中的唯一标识列
             property:订单信息中的唯一标识列所映射到Orders类中的哪个属性          --><id column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><result column="createtime" property="createtime"/><result column="note" property="note"/><!-- 2.配置映射的关联的用户信息  --><!-- association:用于映射关联查询单个对象的信息
             property:要将关联查询的用户信息映射到Orders类中的哪个属性         --><association property="user" javaType="joanna.yan.mybatis.entity.User"><!-- 关联查询用户的唯一标识
                 column:指定唯一标识用户信息的列
                 property:映射到user的哪个属性              --><id column="user_id" property="id"/><result column="username" property="username"/><result column="sex" property="sex"/><result column="address" property="sex"/></association></resultMap>

2.3.4.2定義statement定義

    <!--查询订单,关联查询用户信息,使用ResultMap  --><select id="findOrdersUserResultMap" resultMap="OrdersUserResultMap">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address 
        FROM
          orders,
          USER 
        WHERE orders.user_id = user.id</select>

2.3.4.3mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息,使用resultMappublic List<Orders> findOrdersUserResultMap() throws Exception;
}

2.3. 4.4測試程式

    @Testpublic void findOrdersUserResultMapTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<Orders> list=ordersCustomMapper.findOrdersUserResultMap();
        System.out.println(list);
        sqlSession.close();
    }

2.4 resultType和resultMap實作一對一查詢小結

實作一對一查詢:

resultType:使用resultType實作較為簡單,如果pojo中沒有包含查詢出來的列名,則需要增加列名對應的屬性,即可完成對應。

如果沒有查詢結果的特殊要求,建議使用resultType。

resultMap:需要單獨定義resultMap,實作有點麻煩,如果對查詢結果又特別的要求,使用resultMap可以完成將關聯查詢映射pojo的屬性中。

resultMap可以實現延遲加載,resultType無法實現延遲加載。

3.一對多查詢

3.1需求

查詢訂單及訂單明細的資訊

#3.2sql語句

確定主查詢表:訂單表

決定關聯查詢表:訂單明細表

在一對一查詢基礎上新增訂單明細表關聯即可。

SELECT 
  orders.*,  USER.username,  USER.sex,  USER.address,
  orderdetail.id orderdetail_id,
  orderdetail.items_id,
  orderdetail.items_num,
  orderdetail.orders_idFROM
  orders,  USER,
  orderdetailWHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id

3.3分析

使用resultType將上邊的查詢結果對應到pojo中,訂單資訊的就會重複。

要求:

對orders的對應不能出現重複記錄。

解決:

在Orders.java類別中加入List orderDetails屬性。

最終會將訂單資訊對應到Orders中,訂單所對應的訂單明細會對應到orders中的orderDetails屬性中。

對應成的orders記錄數為兩個(orders資訊不重複)

每個orders中的orderDetails屬性儲存了該訂單所對應的訂單明細。

 3.4在Orders類別中新增list訂單明細屬性

3.5定義resultMap 

    <!--订单及订单明细的resultMap
        使用extends继承,就不需要再配置订单信息和用户信息的映射了      --><resultMap type="joanna.yan.mybatis.entity.Orders" id="OrdersAndOrderDetailResultMap" extends="OrdersUserResultMap"><!-- 1.配置映射的订单信息  --><!-- 2.配置映射的关联的用户信息  --><!-- 使用extends继承,就不需要再配置订单信息和用户信息的映射了 --><!-- 3.配置映射的订单明细信息  --><!-- 订单明细信息
             一个订单关联查询出了多条明细,要使用collection进行映射
             collection:对关联查询到的多条记录映射到集合对象中
             property:将关联查询到多条记录映射到joanna.yan.mybatis.entity.Orders中的哪个属性
              ofType:指定映射到list集合属性中pojo的类型         --><collection property="orderdetails" ofType="joanna.yan.mybatis.entity.Orderdetail"><!-- id:订单明细的唯一标识
                 property:要讲订单明细的唯一标识映射到joanna.yan.mybatis.entity.Orderdetail的哪个属性              --><id column="orderdetail_id" property="id"/><result column="items_id" property="itemsId"/><result column="items_num" property="itemsNum"/><result column="orders_id" property="ordersId"/></collection></resultMap>

3.6mapper. xml

    <!-- 查询订单,关联查询用户及订单明细,使用resultMap --><select id="findOrdersAndOrderDetailResultMap" resultMap="OrdersAndOrderDetailResultMap">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address,
          orderdetail.id orderdetail_id,
          orderdetail.items_id,
          orderdetail.items_num,
          orderdetail.orders_id
        FROM
          orders,
          USER,
          orderdetail
        WHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id</select>

3.7mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息public List<OrdersCustom> findOrdersUser() throws Exception;//查询订单,关联查询用户信息,使用resultMappublic List<Orders> findOrdersUserResultMap() throws Exception;//查询订单(关联用户)及订单明细public List<Orders> findOrdersAndOrderDetailResultMap() throws Exception;
}

3.8測試程式

    @Testpublic void findOrdersAndOrderDetailResultMapTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<Orders> list=ordersCustomMapper.findOrdersAndOrderDetailResultMap();
        System.out.println(list);
        sqlSession.close();
    }

3.9小结

mybatis使用resultMap的collection对关联查询的多条记录映射到有个list集合属性中。

使用resultType实现:

将订单明细映射到orders中的orderdetails中,需要自己处理,使用双重循环遍历,去掉重复记录,将订单明细放在ordertails中。

4.多对多查询

4.1需求

查询用户及用户购买的商品信息。

4.2sql语句

查询主表:用户表

关联表:由于用户和商品没有直接关联,通过订单和订单明细进行关联,所有关联表:orders、orderdetail、items。

SELECT 
  orders.*,  USER.username,  USER.sex,  USER.address,
  orderdetail.id orderdetail_id,
  orderdetail.items_id,
  orderdetail.items_num,
  orderdetail.orders_id,
  items.name items_name,
  items.detail items_detail,
  items.price items_priceFROM
  orders,  USER,
  orderdetail,
  itemsWHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id AND orderdetail.items_id = items.id

4.3映射思路

将用户信息映射到user中。

在User类中添加订单列表属性List orderslist,将用户创建的订单映射到orderslist;

在Orders中田间订单明细列表属性List orderdetails,将订单的明细映射到orderdetails;

在OrderDetail中添加Items属性,将订单明细所对应的商品映射到Items。

4.4 mapper.xml

    <select id="findUserAndItemsResultMap" resultMap="UserAndItemsResultMap">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address,
          orderdetail.id orderdetail_id,
          orderdetail.items_id,
          orderdetail.items_num,
          orderdetail.orders_id,
          items.name items_name,
          items.detail items_detail,
          items.price items_price
        FROM
          orders,
          USER,
          orderdetail,
          items
        WHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id AND orderdetail.items_id = items.id        </select>

4.5定义resultMap

    <!-- 查询用户及购买商品  --><resultMap type="joanna.yan.mybatis.entity.User" id="UserAndItemsResultMap"><!-- 1.用户信息 --><id column="user_id" property="id"/><result column="username" property="username"/><result column="sex" property="sex"/><result column="address" property="address"/><!-- 2.订单信息 --><!-- 一个用户对应多个订单,使用collection映射 --><collection property="ordersList" ofType="joanna.yan.mybatis.entity.Orders"><id column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><result column="createtime" property="createtime"/><result column="note" property="note"/><!-- 3.订单明细  --><!-- 一个订单包括多个明细 --><collection property="orderdetails" ofType="joanna.yan.mybatis.entity.Orderdetail"><id column="orderdetail_id" property="id"/><result column="items_id" property="itemsId"/><result column="items_num" property="itemsNum"/><result column="orders_id" property="ordersId"/><!-- 4.商品信息  --><!-- 一个订单明细对应一个商品 --><association property="items" javaType="joanna.yan.mybatis.entity.Items"><id column="items_id" property="id"/><result column="items_name" property="name"/><result column="items_detail" property="detail"/><result column="items_price" property="price"/></association></collection></collection></resultMap>

4.6mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息public List<OrdersCustom> findOrdersUser() throws Exception;//查询订单,关联查询用户信息,使用resultMappublic List<Orders> findOrdersUserResultMap() throws Exception;//查询订单(关联用户)及订单明细public List<Orders> findOrdersAndOrderDetailResultMap() throws Exception;//查询用户购买商品信息public List<User> findUserAndItemsResultMap() throws Exception;
}

4.7测试程序

    @Testpublic void findUserAndItemsResultMapTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<User> list=ordersCustomMapper.findUserAndItemsResultMap();
        System.out.println(list);
        sqlSession.close();
    }

4.8多对多查询总结

将查询用户购买的商品信息明细清单(用户名、用户地址、购买商品名称、购买商品时间、购买商品数量)

针对上面的需求就使用resultType将查询到的记录映射到一个扩展的pojo中,很简单实现明细清单的功能。

一对多是多对多的特例,如下需求:

查询用户购买的商品信息,用户和商品的关系是多对多关系。

需求1:

查询字段:用户账号、用户名称、用户性别、商品名称、商品价格(最常见)

企业开发中常见明细列表,用户购买商品明细列表,

使用resultType将上边查询列映射到pojo输出。

需求2:

查询字段:用户账号、用户名称、购买商品数量、商品明细(鼠标移上显示明细)

使用resultMap将用户购买的商品明细列表映射到user对象中。

总结:

使用resultMap是针对那些对查询结果映射有特殊要求的功能,比如特殊要求映射成list中包含多个list。

 5.resultMap总结

resultType:

作用:将查询结果按照sql列名pojo属性一致性映射到pojo中。

场合:

  常见一些明细记录的展示,比如用户购买商品明细,将关联查询信息全部展示在页面时,此时可直接使用resultType将每一条记录映射到pojo中,在前端页面遍历list(list中是pojo)即可。

resultMap:

  使用association和collection完成一对一和一对多高级映射(对结果又特殊的映射要求)。

association:

作用:将关联查询信息映射到一个pojo对象中。

场合:

为了方便查询关联信息可以使用association将关联订单信息映射为用户对象的pojo属性中,比如:查询订单及关联用户信息。

  使用resultType无法将查询结果映射到pojo对象的pojo属性中,根据对结果集查询遍历的需要选择使用resultType还是resultMap。

collection:

作用:将关联查询信息映射到一个list集合中。

场合:为了方便擦还行遍历关联信息可以使用collection将关联信息映射到list集合中,比如:查询用户权限范围模块及模块下的菜单,可使用collection将模块映射到模块list中,将菜单列表映射到模块对象的菜单list属性中,这样做册目的也是方便对查询结果集进行遍历查询。

  如果使用resultType无法将查询结果映射到list集合中。 

以上是MyBatis關聯查詢的實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn