欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談MyBatis3 DynamicSql風格語法使用指南

 更新時間:2021年03月05日 11:22:40   作者:LeArn淡然  
這篇文章主要介紹了淺談MyBatis3 DynamicSql風格語法使用指南,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

主要演示DynamicSql風格代碼如何使用,基本能應對大部分使用場景。DynamicSql基本介紹點我查看。

本文主要沿著增、刪、改、查的思路進行介紹,盡量涵蓋日常使用所需。

我這里還是要推薦一下大家看官方文檔,盡量有問題先找官方文檔教程,除非寫的跟屎一樣,但大概率不會。

本次使用的是mybatis-dynamic-sql1.2.1版本

<!-- 集成mybatis -->
<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>2.1.3</version>
</dependency>
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>8.0.22</version>
</dependency>
<!-- MyBatis 生成器 -->
<dependency>
 <groupId>org.mybatis.generator</groupId>
 <artifactId>mybatis-generator-core</artifactId>
 <version>1.4.0</version>
</dependency>
<!-- MyBatis 動態(tài)SQL支持 -->
<dependency>
 <groupId>org.mybatis.dynamic-sql</groupId>
 <artifactId>mybatis-dynamic-sql</artifactId>
 <version>1.2.1</version>
</dependency>


查詢我盡量貼上SQL語句對照著java代碼,方便讀者閱讀和理解。

而且基本都實際運行過,確保沒有問題。

查詢指定列

SELECT 
 id,label,value 
FROM 
 sys_dict
import static com.twj.spirngbasics.server.mapper.SysDictDynamicSqlSupport.*; //注意導入對應DynamicSqlSupport包的靜態(tài)屬性

SelectStatementProvider selectStatement = SqlBuilder.select(id, label, value)
  .from(sysDict)
  .build()
  .render(RenderingStrategies.MYBATIS3);
List<SysDict> test = sysDictMapper.selectMany(selectStatement);

下面完全等價于上面代碼,推薦上方寫法,代碼更整潔。

SelectStatementProvider selectStatement = SqlBuilder.select(SysDictDynamicSqlSupport.id, SysDictDynamicSqlSupport.label, SysDictDynamicSqlSupport.value)
  .from(SysDictDynamicSqlSupport.sysDict)
  .build()
  .render(RenderingStrategies.MYBATIS3);
List<SysDict> list = sysDictMapper.selectMany(selectStatement);
 

可以看到DynamicSql的使用結構完全與sql語句一樣,真香。

查詢所有列

SELECT 
 id,label,value,sort.......
FROM 
 sys_dict
 
SelectStatementProvider selectStatement = SqlBuilder.select(SysDictMapper.selectList)
  .from(SysDictDynamicSqlSupport.sysDict)
  .build()
  .render(RenderingStrategies.MYBATIS3);
List<SysDict> list = sysDictMapper.selectMany(selectStatement);

條件查詢

SELECT
 * 
FROM
 sys_dict 
WHERE
 label = '男' 
 OR label = '女' 
ORDER BY
 `value` ASC
SelectStatementProvider selectStatement = SqlBuilder.select(SysDictMapper.selectList)
  .from(SysDictDynamicSqlSupport.sysDict)
  .where(label, isEqualTo("男"))
  .or(label,isEqualTo("女"))
  .orderBy(value)
  .build()
  .render(RenderingStrategies.MYBATIS3);
List<SysDict> list = sysDictMapper.selectMany(selectStatement);

java這里稍微注意一下,isEqualTo的包引用路徑是在org.mybatis.dynamic.sql.SqlBuilder包下,可以像之前一樣import static org.mybatis.dynamic.sql.SqlBuilder.*;引入所有靜態(tài)方法。

排序:

  • 升序:默認MySQL可以不加ASC即為升序排序,DynamicSql也是如此,指定列即可;
  • 降序:調用descending()即可,以上方例子為例,原orderBy(value)改為orderBy(value.descending())即可。
SELECT
 * 
FROM
 sys_dict 
WHERE
 label IN ( '女', '男' ) 
ORDER BY
 `value`
SelectStatementProvider selectStatement = SqlBuilder.select(SysDictMapper.selectList)
  .from(SysDictDynamicSqlSupport.sysDict)
  .where(label, isIn("女", "男"))
  .orderBy(value)
  .build()
  .render(RenderingStrategies.MYBATIS3);
List<SysDict> list = sysDictMapper.selectMany(selectStatement);

where條件查詢還有很多我就不一一例舉了,我這里有一張官方偷來的表格:

Condition Example Result
Between where(foo, isBetween(x).and(y)) where foo between ? and ?
Equals where(foo, isEqualTo(x)) where foo = ?
Greater Than where(foo, isGreaterThan(x)) where foo > ?
Greater Than or Equals where(foo, isGreaterThanOrEqualTo(x)) where foo >= ?
In where(foo, isIn(x, y)) where foo in (?,?)
In (case insensitive) where(foo, isInCaseInsensitive(x, y)) where upper(foo) in (?,?) (the framework will transform the values for x and y to upper case)
Less Than where(foo, isLessThan(x)) where foo < ?
Less Than or Equals where(foo, isLessThanOrEqualTo(x)) where foo <= ?
Like where(foo, isLike(x)) where foo like ? (the framework DOES NOT add the SQL wild cards to the value - you will need to do that yourself)
Like (case insensitive) where(foo, isLikeCaseInsensitive(x)) where upper(foo) like ? (the framework DOES NOT add the SQL wild cards to the value - you will need to do that yourself, the framework will transform the value of x to upper case)
Not Between where(foo, isNotBetween(x).and(y)) where foo not between ? and ?
Not Equals where(foo, isNotEqualTo(x)) where foo <> ?
Not In where(foo, isNotIn(x, y)) where foo not in (?,?)
Not In (case insensitive) where(foo, isNotInCaseInsensitive(x, y)) where upper(foo) not in (?,?) (the framework will transform the values for x and y to upper case)
Not Like where(foo, isLike(x)) where foo not like ? (the framework DOES NOT add the SQL wild cards to the value - you will need to do that yourself)
Not Like (case insensitive) where(foo, isNotLikeCaseInsensitive(x)) where upper(foo) not like ? (the framework DOES NOT add the SQL wild cards to the value - you will need to do that yourself, the framework will transform the value of x to upper case)
Not Null where(foo, isNotNull()) where foo is not null
Null where(foo, isNull()) where foo is null

子查詢

SELECT
 * 
FROM
 user_resource 
WHERE
 id IN (
 SELECT
 resource_id 
 FROM
 user_role_resource 
 WHERE
 role_id = '1' 
 )
SelectStatementProvider selectStatement = SqlBuilder.select(userResourceMapper.selectList)
  .from(UserResourceDynamicSqlSupport.userResource)
  .where(UserResourceDynamicSqlSupport.id, isIn(
    select(UserRoleResourceDynamicSqlSupport.resourceId)
      .from(UserRoleResourceDynamicSqlSupport.userRoleResource)
      .where(UserRoleResourceDynamicSqlSupport.roleId, isEqualTo("1"))))
  .build()
  .render(RenderingStrategies.MYBATIS3);
List<UserResource> list = userResourceMapper.selectMany(selectStatement);

子查詢還有很多,我這里又有一張官方偷來的表格:

Condition Example Result
Equals where(foo, isEqualTo(select(bar).from(table2).where(bar, isEqualTo(x))) where foo = (select bar from table2 where bar = ?)
Greater Than where(foo, isGreaterThan(select(bar).from(table2).where(bar, isEqualTo(x))) where foo > (select bar from table2 where bar = ?)
Greater Than or Equals where(foo, isGreaterThanOrEqualTo(select(bar).from(table2).where(bar, isEqualTo(x))) where foo >= (select bar from table2 where bar = ?)
In where(foo, isIn(select(bar).from(table2).where(bar, isLessThan(x))) where foo in (select bar from table2 where bar < ?)
Less Than where(foo, isLessThan(select(bar).from(table2).where(bar, isEqualTo(x))) where foo < (select bar from table2 where bar = ?)
Less Than or Equals where(foo, isLessThanOrEqualTo(select(bar).from(table2).where(bar, isEqualTo(x))) where foo <= (select bar from table2 where bar = ?)
Not Equals where(foo, isNotEqualTo(select(bar).from(table2).where(bar, isEqualTo(x))) where foo <> (select bar from table2 where bar = ?)
Not In where(foo, isNotIn(select(bar).from(table2).where(bar, isLessThan(x))) where foo not in (select bar from table2 where bar < ?)

根據業(yè)務邏輯添加條件

詳細看代碼

QueryExpressionDSL<SelectModel>.QueryExpressionWhereBuilder builder = SqlBuilder.select(SysDictMapper.selectList)
  .from(SysDictDynamicSqlSupport.sysDict)
  .where();

if (x)
 builder.where(label, isIn("女", "男"));

if (y)
 builder.where(row,...);

SelectStatementProvider selectStatement = builder.build().render(RenderingStrategies.MYBATIS3);

List<SysDict> list = sysDictMapper.selectMany(selectStatement);

連接查詢

有前面的基礎,連接查詢其實異曲同工,我這里直接貼上官方示例代碼:

SelectStatementProvider selectStatement = select(orderMaster.orderId, orderDate, orderDetail.lineNumber, orderDetail.description, orderDetail.quantity)
   .from(orderMaster, "om")
   .join(orderDetail, "od").on(orderMaster.orderId, equalTo(orderDetail.orderId))
   .build()
   .render(RenderingStrategies.MYBATIS3);

目前支持四種連接類型:

  • .join(...) 內連接
  • .leftJoin(...) 左外連接
  • .rightJoin(...) 右外連接
  • .fullJoin(...) 全連接


新增這里就不附上SQL語句了

新增一條

SysDict sysDict = new SysDict();
sysDict.setLabel("測試");
sysDict.setValue("0");
sysDict.setType("test");
sysDict.setSort(0);
sysDict.setDescription("測試");
sysDict.insert("SYSTEM");
int row = sysDictMapper.insert(sysDict);
System.out.println("成功插入條數:" + row);

批量新增

List<SysDict> list = new ArrayList<>();
for (int i = 1; i < 10; i++) {
 SysDict sysDict = new SysDict();
 sysDict.setLabel("測試");
 sysDict.setValue(String.valueOf(i));
 sysDict.setType("test");
 sysDict.setSort(i);
 sysDict.setDescription("測試");
 sysDict.insert("SYSTEM");
 list.add(sysDict);
}
MultiRowInsertStatementProvider<SysDict> multiRowInsert = SqlBuilder.insertMultiple(list)
  .into(SysDictDynamicSqlSupport.sysDict)
  .map(id).toProperty("id")
  .map(createdBy).toProperty("createdBy")
  .map(createdTime).toProperty("createdTime")
  .map(updateBy).toProperty("updateBy")
  .map(updateTime).toProperty("updateTime")
  .map(dele).toProperty("dele")
  .map(remake).toProperty("remake")
  .map(spare1).toProperty("spare1")
  .map(value).toProperty("value")
  .map(label).toProperty("label")
  .map(type).toProperty("type")
  .map(description).toProperty("description")
  .map(sort).toProperty("sort")
  .build()
  .render(RenderingStrategies.MYBATIS3);

int rows = sysDictMapper.insertMultiple(multiRowInsert);
System.out.println("成功插入條數:" + rows);

批量新增這里需要注意的是map的添加,也可以不加,但我在使用過程中出現過不加map導致批量新增出現某些必填字段明明賦值了數據庫卻報沒有不能為空,猜測應該是轉換成sql語句時into與value沒有一一對應,加上map就沒問題了。

PS:.map可以直接從xxxDictMapper.insert()中copy過來。


//根據主鍵刪除
sysDictMapper.deleteByPrimaryKey("");

//條件刪除
DeleteStatementProvider deleteStatement = deleteFrom(SysDictDynamicSqlSupport.sysDict)
  .where(SysDictDynamicSqlSupport.type, isEqualTo("test"))
  .build()
  .render(RenderingStrategies.MYBATIS3);
sysDictMapper.delete(deleteStatement);


常用的簡單更新主要是下面兩種:

//根據主鍵對所有屬性進行更新
sysDictMapper.updateByPrimaryKey(sysDict);
//根據主鍵對不為null的屬性進行更新
sysDictMapper.updateByPrimaryKeySelective(sysDict);

復雜一點點的:

UpdateStatementProvider updateStatement = update(SysDictDynamicSqlSupport.sysDict)
  .set(remake).equalToNull()
  .where(type, isEqualTo("test"))
  .build()
  .render(RenderingStrategies.MYBATIS3);

int rows = sysDictMapper.update(updateStatement);
System.out.println("成功更新條數:" + rows);

注意set方法,常用的方法有以下:

  • set(column).equalToNull() 將對應列更新為null;
  • set(column).equalTo(T value)將對應列更新為value;
  • set(column).equalToWhenPresent(T value)如果value不能null的話更新列;
  • set(column).equalTo(BasicColumn rightColumn)將一列的值設置為另一列的值,還可以對其加,減等操作。

到此這篇關于淺談MyBatis3 DynamicSql風格語法使用指南的文章就介紹到這了,更多相關MyBatis3 DynamicSql風格內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • SpringMVC實現文件下載功能

    SpringMVC實現文件下載功能

    這篇文章主要為大家詳細介紹了SpringMVC實現文件下載功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-03-03
  • Spring session 獲取當前賬戶登錄數的實例代碼

    Spring session 獲取當前賬戶登錄數的實例代碼

    這篇文章主要介紹了Spring session 獲取當前賬戶登錄數,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-04-04
  • MyBatis中的配置文件詳解

    MyBatis中的配置文件詳解

    在?MyBatis?中,配置文件分為?全局配置文件(核心配置文件)和映射配置文件,本文給大家介紹MyBatis中的配置文件相關知識,感興趣的朋友一起看看吧
    2023-10-10
  • SpringCloud Config使用配置方法

    SpringCloud Config使用配置方法

    這篇文章給大家介紹SpringCloud Config使用及構建配置中心的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2021-07-07
  • Java設計模式之橋梁(Bridge)模式

    Java設計模式之橋梁(Bridge)模式

    這篇文章主要介紹了Java設計模式之橋梁(Bridge)模式,文中有非常詳細的代碼示例,對正在學習Java設計模式的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-05-05
  • SpringBoot 如何實現自定義Redis序列化

    SpringBoot 如何實現自定義Redis序列化

    這篇文章主要介紹了SpringBoot 如何實現自定義Redis序列化方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 每天練一練Java函數與算法Math函數總結與字符串轉換整數

    每天練一練Java函數與算法Math函數總結與字符串轉換整數

    這篇文章主要介紹了Java函數與算法Math函數總結與字符串轉換整數,每天練一練,水平在不知不覺中提高,需要的朋友快過來看看吧
    2021-08-08
  • ThreadLocal作用原理與內存泄露示例解析

    ThreadLocal作用原理與內存泄露示例解析

    這篇文章主要為大家介紹了ThreadLocal作用原理與內存泄露示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-09-09
  • java list常用方法總結

    java list常用方法總結

    這篇文章主要介紹了java list常用方法總結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-11-11
  • mybatisplus的公共字段插入的實現

    mybatisplus的公共字段插入的實現

    這篇文章主要介紹了mybatisplus的公共字段插入,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11

最新評論