程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> MyBatis實踐--動態SQL/關聯查詢

MyBatis實踐--動態SQL/關聯查詢

編輯:MySQL綜合教程

MyBatis實踐--動態SQL/關聯查詢


動態SQL

動態SQL提供了對SQL語句的靈活操作,通過表達式進行判斷,對SQL進行拼接/組裝.


if

對查詢條件進行判斷,如果輸入參數不為空才進行查詢條件的拼接.

mapper
<code class=" hljs vbnet"><select id="selectUser" resulttype="com.fq.domain.User" parametertype="com.fq.domain.User">
    SELECT * FROM user
    
        
            AND id = #{id}
        
        
            AND name = #{name}
        
        
            AND password = #{password}
        
    
</select></code>

會自動處理第一個AND(MyBatis還提供了自定義行為的元素, 詳細可參考MyBatis文檔).

UserDAO
List selectUser(User user) throws Exception;
Client
@Test
public void selectUserClient() throws Exception {
    UserDAO dao = session.getMapper(UserDAO.class);
    User user = dao.selectUser(new User(null, null, "new_password"));
    System.out.println(user);
}

由於id與name為null, 因此這兩個條件不會拼接在SQL中,這一點可以調試時日志中看出.


choose/when/otherwise

有些時候,我們並不想用到所有的條件語句,而只想從中選擇一二.針對這種情況,MyBatis提供了元素,他有點像Java中的switch.

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><select id="selectUser" resulttype="com.fq.domain.User" parametertype="com.fq.domain.User">
    SELECT * FROM user
    
        
            
                AND id = #{id}
            
            
                AND name = #{name}
            
            
                AND password = #{password}
            
        
    
</select></code></code></code></code>

set

用於動態更新語句的解決方案為,set元素可以被用於動態包含需要更新的列, 而捨去其他的.


    UPDATE user
    
        
            name = #{name} ,
        
        
            password = #{password} ,
        
    
    WHERE id = #{id};

foreach

使用foreach可以實現向SQL中傳遞數組或List:

傳入List

查詢多個id的用戶信息, 可以由下面兩種SQL實現:

SELECT * FROM user WHERE (id = ? OR id = ? OR id = ?);
SELECT * FROM user WHERE id IN (?, ?, ?, ?);

因此其foreach的定義也有如下兩種方案:

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><select id="selectUser" parametertype="java.util.List" resulttype="com.fq.domain.User">
    SELECT *
    FROM user
    
        
            
                id = #{id}
            
        
    
</select></code></code></code></code></code></code></code>
<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><select id="selectUser" parametertype="java.util.List" resulttype="com.fq.domain.User">
    SELECT *
    FROM user
    
        
            
                #{id}
            
        
    
</select></code></code></code></code></code></code></code></code>
元素 描述 collection SQL解析的參數名 index 循環下標 item 單個元素的名 open 循環開始輸出 close 循環結束輸出 separator 中間分隔輸出

傳遞List作為parameterType時,SQL解析參數名固定為list.

UserDAO
List selectUser(List ids) throws Exception;

批量插入用戶案例

mapper

    INSERT INTO user(name, password) VALUES
    
        
            (#{user.name}, #{user.password})
        
    
UserDAO
void insertUserList(List users) throws Exception;
Client
@Test
public void insertUserListClient() throws Exception {
    UserDAO dao = session.getMapper(UserDAO.class);
    dao.insertUserList(Lists.newArrayList(new User(null, "mojia5", "mojia5"), new User(null, "mojia6", "mojia6"), new User(null, "mojia7", "mojia7")));
}

傳入數組

mapper
<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs xml"><code class=" hljs java"><code class=" hljs java"><code class=" hljs cs"><select id="selectUser" parametertype="Object[]" resulttype="com.fq.domain.User">
    SELECT *
    FROM user
    
        
            
                #{id}
            
        
    
</select></code></code></code></code></code></code></code></code></code></code></code></code></code>

與List類似,傳遞數組作為parameterType時,SQL解析參數名固定為array.

UserDAO
List selectUser(Integer[] ids) throws Exception;

SQL片段

可以將一段公共的SQL語句抽取出來, 作為一個SQL片段, 供其他SQL調用:

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs xml"><code class=" hljs java"><code class=" hljs java"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs vbnet"><sql id="user_where">
    <if test="id != null">
        AND id = #{id}
    </if>
    <if test="name != null">
        AND name = #{name}
    </if>
    <if test="password != null">
        AND password = #{password}
    </if>
</sql>

<select id="selectUser" resulttype="com.fq.domain.User" parametertype="com.fq.domain.User">
    SELECT * FROM user
    
        
    
</select></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

經驗:最好基於單表定義SQL片段,而且在SQL片段中不要包含/之類的標簽,這樣可以保證SQL片段重用度更高.


關聯查詢

數據模型分析思路

每張表的數據內容:分模塊對每張表記錄的內容進行熟悉,相當於學習系統需求/功能. 每張表重要的字段:非空字段/外鍵字段等. 表與表之間的數據庫級別關系: 外鍵關系. 表與表之間的業務關系:建立在某個業務的基礎上去分析.

訂單/商品數據模型
\

表內容
user: 購買商品的用戶信息 order: 用戶創建的訂單 orderdetail: 訂單詳細(購買商品信息) item: 商品信息 表與表之間的業務關系:
user/order:
user -> order: 一對多 order -> user: 一對一 order/orderdetail:
order -> orderdetail:一對多 orderdetail -> order:一對一 orderdetail/item:
orderdetail -> item:一對一 item -> orderdetail:一對多

‘一對一’查詢

需求: 查詢訂單信息,關聯查詢(創建訂單的)用戶信息.

由以上分析可知主查詢為order表,而order -> user關系為一對一, 因此使用resultMap將查詢結果的訂單信息映射到Order中,將用戶信息映射到Order中的User屬性.

PO: 改造User
public class User implements Serializable {

    private Integer id;

    private String username;

    private Date birthday;

    private Integer sex;

    private String address;

    // ...
}
PO: 新增Order, 將User組合到Order中:
public class Order implements Serializable {

    private Integer id;

    private Integer userId;

    private String number;

    private Date createTime;

    private String note;

    private User user;

    // ...
}
mapper
<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs xml"><code class=" hljs java"><code class=" hljs java"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs vbnet"><code class=" hljs java"><code class=" hljs java"><code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20%3F%2D%2D%3E-->

<mapper namespace="com.fq.mybatis.OrderDAO">

    <cache type="org.mybatis.caches.ehcache.EhcacheCache">

    <resultmap id="order_user_map" type="com.fq.domain.Order">
        <id column="id" property="id">
        <result column="user_id" property="userId">
        <result column="number" property="number">
        <result column="create_time" property="createTime">
        <result column="note" property="note">

        <association property="user" javatype="com.fq.domain.User">
            <id column="user_id" property="id">
            <result column="username" property="username">
            <result column="birthday" property="birthday">
            <result column="sex" property="sex">
            <result column="address" property="address">
        </result></result></result></result></id></association>
    </result></result></result></result></id></resultmap>

    <select id="selectOrderWithUser" resultmap="order_user_map">
        SELECT
        `order`.*,
        username,
        birthday,
        sex,
        address
        FROM `order`, user
        WHERE `order`.user_id = user.id AND `order`.id = #{0};
    </select>

</cache></mapper></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

association: 映射關聯查詢的單條記錄(將關聯查詢信息映射到PO對象屬性).

OrderDAO
public interface OrderDAO {
    Order selectOrderWithUser(Integer id) throws Exception;
}
Client
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
public class OrderDAOClient {

    @Autowired
    private OrderDAO dao;

    @Test
    public void client() throws Exception {
        Order order = dao.selectOrderWithUser(3);
        System.out.println(order);
    }
}

‘一對多’查詢

需求: 查詢訂單及訂單明細的信息(一對多).

PO: 定義OrderDetail,並在Order中添加List orderDetails訂單明細屬性:
public class OrderDetail implements Serializable {

    private Integer id;

    private Integer orderId;

    private Integer itemId;

    private Integer itemNumber;

    // ...
}
mapper
<code class=" hljs java"><code class=" hljs vbnet"><resultmap id="order_user_detail_map" type="com.fq.domain.Order" extends="order_user_map">
    <collection property="orderDetails" oftype="com.fq.domain.OrderDetail">
        <id column="order_detail_id" property="id">
        <result column="item_id" property="itemId">
        <result column="item_num" property="itemNumber">
        <result column="order_id" property="orderId">
    </result></result></result></id></collection>
</resultmap>

<select id="selectOrderWithDetail" resultmap="order_user_detail_map">
    SELECT
    `order`.*,
    username,
    birthday,
    sex,
    address,
    orderdetail.id order_detail_id,
    item_id,
    item_num,
    order_id
    FROM `order`, user, orderdetail
    WHERE `order`.user_id = user.id AND `order`.id = orderdetail.order_id AND `order`.id = #{0};
</select></code></code>
元素 描述 property 指定關聯查詢的結果集存儲到的屬性 ofType 指定關聯查詢結果集中的對象類型 OrderDAO
Order selectOrderWithDetail(Integer id) throws Exception;

‘多對多’查詢

需求: 查詢用戶及用戶購買商品信息.

由於User表與Item表沒有直接關聯,因此只能通過Order表與OrderDetail表進行關聯.

思路:
1) 將用戶信息映射到User中.
2) 在User中添加List訂單列表屬性,將用戶創建的訂單映射到orders.
3) 在Order中添加List訂單明細列表屬性,將訂單的明細映射到orderDetails.
4) 在OrderDetail中添加Item屬性,將訂單明細所對應的商品映射到item.

PO: Item

public class Item {

    private Integer id;

    private String name;

    private Float price;

    private String detail;

    private String pic;

    private Date createTime;

    //...
}
mapper
<code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs mathematica"><code class=" hljs cs"><code class=" hljs applescript"><resultmap id="user_item_map" type="com.fq.domain.User">
    <id column="id" property="id">
    <result column="username" property="username">
    <result column="birthday" property="birthday">
    <result column="sex" property="sex">
    <result column="address" property="address">

    <collection property="orders" oftype="com.fq.domain.Order">
        <id column="order_id" property="id">
        <result column="id" property="userId">
        <result column="order_create_time" property="createTime">
        <result column="order_note" property="note">
        <result column="order_number" property="number">

        <collection property="orderDetails" oftype="com.fq.domain.OrderDetail">
            <id column="order_detail_id" property="id">
            <result column="order_id" property="orderId">
            <result column="item_id" property="itemId">
            <result column="order_item_num" property="itemNumber">

            <association property="item" javatype="com.fq.domain.Item">
                <id column="item_id" property="id">
                <result column="item_create_time" property="createTime">
                <result column="item_detail" property="detail">
                <result column="item_name" property="name">
                <result column="item_price" property="price">
                <result column="item_pic" property="pic">
            </result></result></result></result></result></id></association>
        </result></result></result></id></collection>
    </result></result></result></result></id></collection>
</result></result></result></result></id></resultmap>

<select id="selectUserItem" resultmap="user_item_map">
    SELECT
    user.*,
    `order`.id           order_id,
    `order`.create_time   order_create_time,
    `order`.note         order_note,
    `order`.number       order_number,
    orderdetail.id       order_detail_id,
    orderdetail.item_num order_item_num,
    item.id              item_id,
    item.create_time      item_create_time,
    item.detail          item_detail,
    item.name            item_name,
    item.price           item_price,
    item.pic             item_pic
    FROM user, item, `order`, orderdetail
    WHERE `order`.user_id = user.id AND orderdetail.order_id = `order`.id AND orderdetail.item_id = item.id ;
</select></code></code></code></code></code>
OrderDAO
List selectUserItem() throws Exception;

resultMap小結:

使用和可以完成一對一和一對多的高級映射.

association: 將關聯查詢信息映射到一個PO對象中. collection: 將關聯查詢信息映射到一個集合中.

延遲加載

關聯查詢時,使用MyBatis 延遲加載 特性可有效減輕數據庫壓力.首次查詢只查詢主表信息,等需要時再去查詢關聯表信息.的/具備延遲加載功能.

需求: 查詢訂單信息並關聯查詢用戶信息.

延遲加載開關

在MyBatis核心配置文件(mybatis-configuration.xml)中配置:
1) lazyLoadingEnabled : 設置是否懶加載.默認false,則所有關聯查詢都會被初始化加載.
2) aggressiveLazyLoading : 設置是否積極加載. 默認true,所有關聯屬性被初始化加載.

Settings配置:

<code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs mathematica"><code class=" hljs cs"><code class=" hljs applescript"><code class=" hljs php"><code class=" hljs xml"><settings>
    <setting name="cacheEnabled" value="true">
    <setting name="lazyLoadingEnabled" value="true">
    <setting name="aggressiveLazyLoading" value="false">
</setting></setting></setting></settings></code></code></code></code></code></code></code>

Mapper

只查詢訂單信息
<code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs mathematica"><code class=" hljs cs"><code class=" hljs applescript"><code class=" hljs php"><code class=" hljs xml"><code class=" hljs applescript"><resultmap id="order_user_map" type="com.fq.domain.Order">
    <id column="id" property="id">
    <result column="user_id" property="userId">
    <result column="number" property="number">
    <result column="create_time" property="createTime">
    <result column="note" property="note">

    <association property="user" javatype="com.fq.domain.User" select="com.fq.mybatis.UserDAO.selectUserById" column="user_id">
</association></result></result></result></result></id></resultmap>

<select id="selectOrderWithUser" resultmap="order_user_map">
    SELECT *
    FROM `order`;
</select></code></code></code></code></code></code></code></code>
元素 描述 select 指定關聯查詢Statement為com.fq.mybatis.UserDAO.selectUserById. column 指定關聯查詢時將users_id值傳入selectUserById. 關聯查詢用戶信息(namespace為com.fq.mybatis.UserDAO)
<code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs mathematica"><code class=" hljs cs"><code class=" hljs applescript"><code class=" hljs php"><code class=" hljs xml"><code class=" hljs applescript"><code class=" hljs vbnet"><select id="selectUserById" parametertype="java.lang.Integer" resulttype="com.fq.domain.User">
    SELECT *
    FROM user
    WHERE id = #{id};
</select></code></code></code></code></code></code></code></code></code>

將上面查詢到的訂單信息中的user_id傳入selectUserById來關聯查詢用戶信息.

OrderDAO(同前)
List selectOrderWithUser() throws Exception;
Client
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
public class OrderDAOClient {

    @Autowired
    private OrderDAO dao;

    @Test
    public void client() throws Exception {
        List orders = dao.selectOrderWithUser();
        for (Order order : orders) {
            System.out.println(order.getUser());
        }
    }
}

debug上面Client, 觀察log信息,會發現只有當確實需要User信息時才會調用selectUserById.


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved