第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

OGNL 表達式

1. 前言

MyBatis 的動態(tài) SQL 廣泛應用到了OGNL 表達式,OGNL 表達式可以靈活的組裝 SQL 語句,從而完成更多的功能。OGNL 易學易用,與 Java 代碼幾乎一致,本小節(jié)我們將系統(tǒng)的介紹 OGNL 表達式在 MyBatis 中的使用。

2. 定義

慕課解釋:OGNL 全稱 Object-Graph Navigation Language,是 Java 中的一個開源的表達式語言,用于訪問對象數(shù)據(jù)。

3. 介紹

3.1 實例

OGNL 最常用于 if 標簽中,用于判斷條件是否滿足,如下:

<if test="age != null">
  AND age = #{age}
</if>

if 標簽的 test 屬性就是個典型的 OGNL 表達式。age != null表示當 age 不為 null 的時候 if 成立,則動態(tài)的向 SQL 中插入標簽內的 SQL 代碼段。

3.2 常見的 OGNL 表達式

在 MyBatis 中常見的 OGNL 表達式如下:

  1. e1 or e2:或關系
  2. e1 and e2:與關系
  3. e1 == e2 或者 e1 eq e2:相等
  4. e1 != e2 或者 e1 neq e2:不等
  5. e1 lt e2 ;e1 < e2;e1 gt e2;e1 > e2;e1 lte e2;e1 <= e2;e1 gte e2;e1 >= e2:比較關系
  6. e1 + e2;e1 - e2;e1 * e2;e1 / e2;e1 % e2:運算關系
  7. !e 或者 not e:非,取反
  8. e.method(args):調用對象方法
  9. e.property:訪問屬性值
  10. e1[e2]:訪問數(shù)組、鏈表(e2 為序號)或者 Map(e2 為鍵值)

其中 1~4 以及 9~10 都是特別常用的幾種情況,而其它的情況不利于 SQL 的維護,因此并不常見。

TIPS: 提示, 如果你熟悉 Python 的話,會發(fā)現(xiàn) OGNL 表達式完全就是在寫 Python。

4. 實踐

下面我們就來以實例來看一看 OGNL 表達式。

有一個名為 pedro 的 User 對象,如下:

User pedro = new User();
pedro.setUsername("pedro");
pedro.setTags(Arrays.asList("admin", "man"));
pedro.setAge(23);

4.1 訪問屬性

訪問用戶的 username 屬性,OGNL 表達式為pedro.username,結果為:

# pedro.username
pedro

4.2 訪問列表

訪問用戶的第一個標簽,OGNL 表達式為pedro.tags[0],結果為:

# pedro.tags[0]
admin

4.3 比較

比較用戶標簽長度是否大于 1,OGNL 表達式為pedro.tags[0],結果為:

# pedro.tags.size > 1
true

4.4 運算

用戶年齡加上一個整數(shù) 22,OGNL 表達式為pedro.age + 22,結果為:

# pedro.age + 22
45

4.5 方法調用

將用戶年齡全部大寫,OGNL 表達式為pedro.username.toUpperCase,結果為:

# pedro.username.toUpperCase
PEDRO

5. 小結

  • OGNL 表達式是 MyBatis 動態(tài) SQL 的核心,小巧精致卻功能強大,易學易用。