序言
MyBatis,大家都知道,半自動的ORM框架,原來叫ibatis,后來好像是10年apache軟件基金組織把它托管給了goole code,就重新命名了MyBatis,功能相對以前更強大了。它相對全自動的持久層框架Hibernate,更加靈活,更輕量級,這點我還是深有體會的。
MyBatis的一個強大特性之一就是動態(tài)SQL能力了,能省去我們很多串聯(lián)判斷拼接SQL的痛苦,根據(jù)項目而定,在一定的場合下使用,能大大減少程序的代碼量和復(fù)雜程度,不過還是不是過度太過復(fù)雜的使用,以免不利于后期的維護和擴展。
動態(tài)SQL
動態(tài)SQL提供了對SQL語句的靈活操作,通過表達式進行判斷,對SQL進行拼接/組裝.
if
對查詢條件進行判斷,如果輸入?yún)?shù)不為空才進行查詢條件的拼接.
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
code class="hljs vbnet">code class="hljs php">Listuser> selectUser(User user) throws Exception;/user>/code>/code>
Client
code class="hljs vbnet">code class="hljs php">code class="hljs java">@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);
}/code>/code>/code>
由于id與name為null, 因此這兩個條件不會拼接在SQL中,這一點可以調(diào)試時日志中看出.
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
用于動態(tài)更新語句的解決方案為,set元素可以被用于動態(tài)包含需要更新的列, 而舍去其他的.
code class="hljs vbnet">code class="hljs php">code class="hljs java">code class="hljs vbnet">code class="hljs applescript">update id="updateUserById" parametertype="com.fq.domain.User">
UPDATE user
set>
if test="name != null">
name = #{name} ,
/if>
if test="password != null">
password = #{password} ,
/if>
/set>
WHERE id = #{id};
/update>/code>/code>/code>/code>/code>
foreach
使用foreach可以實現(xiàn)向SQL中傳遞數(shù)組或List:
傳入List
查詢多個id的用戶信息, 可以由下面兩種SQL實現(xiàn):
code class="hljs vbnet">code class="hljs php">code class="hljs java">code class="hljs vbnet">code class="hljs applescript">code class="hljs sql">SELECT * FROM user WHERE (id = ? OR id = ? OR id = ?);
SELECT * FROM user WHERE id IN (?, ?, ?, ?);/code>/code>/code>/code>/code>/code>
因此其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解析的參數(shù)名
index 循環(huán)下標(biāo)
item 單個元素的名
open 循環(huán)開始輸出
close 循環(huán)結(jié)束輸出
separator 中間分隔輸出
傳遞List作為parameterType時,SQL解析參數(shù)名固定為list.
UserDAO
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">Listuser> selectUser(Listinteger> ids) throws Exception;/integer>/user>/code>/code>/code>/code>/code>/code>/code>/code>/code>
批量插入用戶案例
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">insert id="insertUserList" parametertype="java.util.List">
INSERT INTO user(name, password) VALUES
if test="list != null and list.size != 0">
foreach collection="list" item="user" separator=",">
(#{user.name}, #{user.password})
/foreach>
/if>
/insert>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
UserDAO
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">void insertUserList(Listuser> users) throws Exception;/user>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
Client
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">@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")));
}/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
傳入數(shù)組
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類似,傳遞數(shù)組作為parameterType時,SQL解析參數(shù)名固定為array.
UserDAO
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">Listuser> selectUser(Integer[] ids) throws Exception;/user>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
SQL片段
可以將一段公共的SQL語句抽取出來, 作為一個SQL片段, 供其他SQL調(diào)用:
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>
經(jīng)驗:最好基于單表定義SQL片段,而且在SQL片段中不要包含/之類的標(biāo)簽,這樣可以保證SQL片段重用度更高.
關(guān)聯(lián)查詢
數(shù)據(jù)模型分析思路
每張表的數(shù)據(jù)內(nèi)容:分模塊對每張表記錄的內(nèi)容進行熟悉,相當(dāng)于學(xué)習(xí)系統(tǒng)需求/功能. 每張表重要的字段:非空字段/外鍵字段等. 表與表之間的數(shù)據(jù)庫級別關(guān)系: 外鍵關(guān)系. 表與表之間的業(yè)務(wù)關(guān)系:建立在某個業(yè)務(wù)的基礎(chǔ)上去分析.
訂單/商品數(shù)據(jù)模型
表內(nèi)容
user: 購買商品的用戶信息 order: 用戶創(chuàng)建的訂單 orderdetail: 訂單詳細(購買商品信息) item: 商品信息 表與表之間的業(yè)務(wù)關(guān)系:
user/order:
user -> order: 一對多 order -> user: 一對一 order/orderdetail:
order -> orderdetail:一對多 orderdetail -> order:一對一 orderdetail/item:
orderdetail -> item:一對一 item -> orderdetail:一對多
‘一對一'查詢
需求: 查詢訂單信息,關(guān)聯(lián)查詢(創(chuàng)建訂單的)用戶信息.
由以上分析可知主查詢?yōu)閛rder表,而order -> user關(guān)系為一對一, 因此使用resultMap將查詢結(jié)果的訂單信息映射到Order中,將用戶信息映射到Order中的User屬性.
PO: 改造User
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">public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private Integer sex;
private String address;
// ..
}/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
PO: 新增Order, 將User組合到Order中:
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">public class Order implements Serializable {
private Integer id;
private Integer userId;
private String number;
private Date createTime;
private String note;
private User user;
// ...
}/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
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: 映射關(guān)聯(lián)查詢的單條記錄(將關(guān)聯(lián)查詢信息映射到PO對象屬性).
OrderDAO
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">code class="hljs cs">public interface OrderDAO {
Order selectOrderWithUser(Integer id) throws Exception;
}/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
Client
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">code class="hljs cs">code class="hljs java">@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);
}
}/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
‘一對多'查詢
需求: 查詢訂單及訂單明細的信息(一對多).
PO: 定義OrderDetail,并在Order中添加List orderDetails訂單明細屬性:
code class="hljs java">public class OrderDetail implements Serializable {
private Integer id;
private Integer orderId;
private Integer itemId;
private Integer itemNumber;
// ...
}/code>
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 指定關(guān)聯(lián)查詢的結(jié)果集存儲到的屬性
ofType 指定關(guān)聯(lián)查詢結(jié)果集中的對象類型OrderDAO
code class="hljs java">code class="hljs vbnet">code class="hljs mathematica">Order selectOrderWithDetail(Integer id) throws Exception;/code>/code>/code>
‘多對多'查詢
需求: 查詢用戶及用戶購買商品信息.
由于User表與Item表沒有直接關(guān)聯(lián),因此只能通過Order表與OrderDetail表進行關(guān)聯(lián).
思路:
1) 將用戶信息映射到User中.
2) 在User中添加List訂單列表屬性,將用戶創(chuàng)建的訂單映射到orders.
3) 在Order中添加List訂單明細列表屬性,將訂單的明細映射到orderDetails.
4) 在OrderDetail中添加Item屬性,將訂單明細所對應(yīng)的商品映射到item.
PO: Item
code class="hljs java">code class="hljs vbnet">code class="hljs mathematica">code class="hljs cs">public class Item {
private Integer id;
private String name;
private Float price;
private String detail;
private String pic;
private Date createTime;
//...
}/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">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
code class="hljs java">code class="hljs vbnet">
code class="hljs mathematica">
code class="hljs cs">
code class="hljs applescript">
code class="hljs php">Listuser> selectUserItem() throws Exception;/user>
/code>/code>/code>/code>/code>/code>
resultMap小結(jié):
使用和可以完成一對一和一對多的高級映射.
association: 將關(guān)聯(lián)查詢信息映射到一個PO對象中. collection: 將關(guān)聯(lián)查詢信息映射到一個集合中.
延遲加載
關(guān)聯(lián)查詢時,使用MyBatis 延遲加載 特性可有效減輕數(shù)據(jù)庫壓力.首次查詢只查詢主表信息,等需要時再去查詢關(guān)聯(lián)表信息.的/具備延遲加載功能.
需求: 查詢訂單信息并關(guān)聯(lián)查詢用戶信息.
延遲加載開關(guān)
在MyBatis核心配置文件(mybatis-configuration.xml)中配置:
1) lazyLoadingEnabled : 設(shè)置是否懶加載.默認false,則所有關(guān)聯(lián)查詢都會被初始化加載.
2) aggressiveLazyLoading : 設(shè)置是否積極加載. 默認true,所有關(guān)聯(lián)屬性被初始化加載.
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 指定關(guān)聯(lián)查詢Statement為com.fq.mybatis.UserDAO.selectUserById.
column 指定關(guān)聯(lián)查詢時將users_id值傳入selectUserById.關(guān)聯(lián)查詢用戶信息(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來關(guān)聯(lián)查詢用戶信息.
OrderDAO(同前)
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">
code class="hljs mathematica">Listorder> selectOrderWithUser() throws Exception;/order>
/code>
/code>/code>/code>/code>/code>/code>/code>/code>/code>
Client
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">code class="hljs mathematica">code class="hljs java">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
public class OrderDAOClient {
@Autowired
private OrderDAO dao;
@Test
public void client() throws Exception {
Listorder> orders = dao.selectOrderWithUser();
for (Order order : orders) {
System.out.println(order.getUser());
}
}
}/order>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>/code>
debug上面Client, 觀察log信息,會發(fā)現(xiàn)只有當(dāng)確實需要User信息時才會調(diào)用selectUserById.
以上所述是小編給大家介紹的mybatis實踐之動態(tài)sql及關(guān)聯(lián)查詢,希望對大家以上幫助!
您可能感興趣的文章:- 使用 Apache Superset 可視化 ClickHouse 數(shù)據(jù)的兩種方法
- superset在linux和windows下的安裝和部署詳細教程
- JPA多條件復(fù)雜SQL動態(tài)分頁查詢功能
- Mybatis模糊查詢和動態(tài)sql語句的用法
- Java的MyBatis框架中對數(shù)據(jù)庫進行動態(tài)SQL查詢的教程
- Superset實現(xiàn)動態(tài)SQL查詢功能