程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> MSSQL >> MyBatis理論之靜態SQL及聯系關系查詢

MyBatis理論之靜態SQL及聯系關系查詢

編輯:MSSQL

MyBatis理論之靜態SQL及聯系關系查詢。本站提示廣大學習愛好者:(MyBatis理論之靜態SQL及聯系關系查詢)文章只能為提供參考,不一定能成為您想要的結果。以下是MyBatis理論之靜態SQL及聯系關系查詢正文


序文

MyBatis,年夜家都曉得,半主動的ORM框架,本來叫ibatis,後來似乎是10年apache軟件基金組織把它托管給了goole code,就從新定名了MyBatis,功效絕對之前更壯大了。它絕對全主動的耐久層框架Hibernate,加倍靈巧,更輕量級,這點我照樣深有領會的。

MyBatis的一個壯大特征之一就是靜態SQL才能了,能省去我們許多串連斷定拼接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

<code class="hljs vbnet"><code class="hljs php">List<user> 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中,這一點可以調試光陰志中看出.

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元素可以被用於靜態包括須要更新的列, 而捨去其他的.

<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可以完成向SQL中傳遞數組或List:

傳入List

查詢多個id的用戶信息, 可以由上面兩種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">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解析的參數名
index 輪回下標
item 單個元素的名
open 輪回開端輸入
close 輪回停止輸入
separator 中央分隔輸入

傳遞List作為parameterType時,SQL解析參數名固定為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">List<user> selectUser(List<integer> 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(List<user> 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>

傳入數組

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

<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">List<user> selectUser(Integer[] ids) throws Exception;</user></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

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

<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: 映照聯系關系查詢的單筆記錄(將聯系關系查詢信息映照到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 指定聯系關系查詢的成果集存儲到的屬性

ofType 指定聯系關系查詢成果集中的對象類型OrderDAO

<code class="hljs java"><code class="hljs vbnet"><code class="hljs mathematica">Order selectOrderWithDetail(Integer id) throws Exception;</code></code></code>

‘多對多'查詢

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

因為User表與Item表沒有直接聯系關系,是以只能經由過程Order表與OrderDetail表停止聯系關系.

思緒:

1) 將用戶信息映照到User中.
2) 在User中添加List定單列表屬性,將用戶創立的定單映照到orders.
3) 在Order中添加List定單明細列表屬性,將定單的明細映照到orderDetails.
4) 在OrderDetail中添加Item屬性,將定單明細所對應的商品映照到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">List<user> selectUserItem() throws Exception;</user>
</code></code></code></code></code></code>

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(同前)

<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">List<order> 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 {
List<order> 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信息,會發明只要當確切須要User信息時才會挪用selectUserById.

以上所述是小編給年夜家引見的mybatis理論之靜態sql及聯系關系查詢,願望對年夜家以上贊助!

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