1. 程式人生 > >springboot之通用mapper擴充套件通用介面和Example 用法

springboot之通用mapper擴充套件通用介面和Example 用法

專案中提供了大量現成的方法,這些方法可以作為擴充套件時的參考。

例如 selectAll 方法。

首先定義介面:

@RegisterMapper
public interface SelectAllMapper<T> {

    /**
     * 查詢全部結果
     *
     * @return
     */
    @SelectProvider(type = MySelectProvider.class, method = "dynamicSQL")
    List<T> selectAll();
}

其中 MySelectProvider 是你要實現的一個類,該類需要繼承 MapperTemplate。

    @RegisterMapper 註解可以避免 mappers 引數配置,通用 Mapper 檢測到該介面被繼承時,會自動註冊。

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

public class MySelectProvider extends MapperTemplate {

    public BaseSelectProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }
 
    /**
     * 查詢全部結果
     *
     * @param ms
     * @return
     */
    public String selectAll(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        //修改返回值型別為實體型別
        setResultType(ms, entityClass);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.selectAllColumns(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.orderByDefault(entityClass));
        return sql.toString();
    }
}

其中 selectAll 方法名要和介面中定義的方法名一致。其次就是該方法的引數為 MappedStatement 型別。

在 selectAll 方法中,首先是獲取了當前介面的實體型別:

final Class<?> entityClass = getEntityClass(ms);

因為介面返回值型別為 List<T>,MyBatis 會認為返回值型別為 List<Object>,這和我們想要的實體型別不一樣,所以下一行程式碼就是設定返回值型別:

setResultType(ms, entityClass);

    注意,只有返回 T 或者 List 時需要設定,返回 int 型別時不需要設定。

接下來就是純粹的拼接 XML 形式的 SQL 了。

//select col1,col2...
sql.append(SqlHelper.selectAllColumns(entityClass));
//from tablename - 支援動態表名
sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
//order by xxx
sql.append(SqlHelper.orderByDefault(entityClass));

這是其中最簡單的一個方法實現。當你想要實現某種方法時,可以從已有的例子中找一個最接近的方法,在此基礎上進行修改。

Example 用法:

通用 Mapper 中的 Example 方法有兩大類定義,一個引數和兩個引數的,例如下面兩個:

List<T> selectByExample(Object example);

int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);

所有 Example 方法中的 example 型別都是 Object 型別,這是因為通用 Mapper 支援所有符合 Example 結構的引數,例如通過 MBG 生成的 CountryExample、UserExample 類。還有通用 Mapper 中提供的通用 Example,以及支援 Java8 方法引用的 Weekend 型別。

通用 Mapper 中的 Example 方法有兩大類定義,一個引數和兩個引數的,例如下面兩個:

List<T> selectByExample(Object example);

int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);

所有 Example 方法中的 example 型別都是 Object 型別,這是因為通用 Mapper 支援所有符合 Example 結構的引數,例如通過 MBG 生成的 CountryExample、UserExample 類。還有通用 Mapper 中提供的通用 Example,以及支援 Java8 方法引用的 Weekend 型別。

通用 Mapper 中的 Example 方法有兩大類定義,一個引數和兩個引數的,例如下面兩個:

List<T> selectByExample(Object example);

int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);

所有 Example 方法中的 example 型別都是 Object 型別,這是因為通用 Mapper 支援所有符合 Example 結構的引數,例如通過 MBG 生成的 CountryExample、UserExample 類。還有通用 Mapper 中提供的通用 Example,以及支援 Java8 方法引用的 Weekend 型別。

配置中有一個和 Example 有關的 引數詳情參照通用mapper配置中有一個和 Example 有關的引數

MBG 生成的 Example

用法如下:

CountryExample example = new CountryExample();
example.createCriteria().andCountrynameLike("A%");
example.or().andIdGreaterThan(100);
example.setDistinct(true);
int count = mapper.deleteByExample(example);

對於的 SQL 日誌如下:

DEBUG [main] - ==>  Preparing: DELETE FROM country WHERE ( countryname like ? ) or ( Id > ? )
DEBUG [main] - ==> Parameters: A%(String), 100(Integer)
DEBUG [main] - <==    Updates: 95

生成的 CountryExample 中包含了和欄位相關的多種方法,根據自己的需要設定相應的條件即可。
通用 Example

這是由通用 Mapper 提供的一個類,這個類和 MBG 生成的相比,需要自己設定屬性名。這個類還額外提供了更多的方法。
6.2.1 查詢

示例:

Example example = new Example(Country.class);
example.setForUpdate(true);
example.createCriteria().andGreaterThan("id", 100).andLessThan("id",151);
example.or().andLessThan("id", 41);
List<Country> countries = mapper.selectByExample(example);

日誌:

DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country WHERE ( id > ? and id < ? ) or ( id < ? ) ORDER BY id desc FOR UPDATE
DEBUG [main] - ==> Parameters: 100(Integer), 151(Integer), 41(Integer)
DEBUG [main] - <==      Total: 90

6.2.2 動態 SQL

示例:

Example example = new Example(Country.class);
Example.Criteria criteria = example.createCriteria();
if(query.getCountryname() != null){
    criteria.andLike("countryname", query.getCountryname() + "%");
}
if(query.getId() != null){
    criteria.andGreaterThan("id", query.getId());
}
List<Country> countries = mapper.selectByExample(example);

日誌:

DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country WHERE ( countryname like ? ) ORDER BY id desc
DEBUG [main] - ==> Parameters: China%(String)
DEBUG [main] - <==      Total: 1

6.2.3 排序

示例:

Example example = new Example(Country.class);
example.orderBy("id").desc().orderBy("countryname").orderBy("countrycode").asc();
List<Country> countries = mapper.selectByExample(example);

日誌:

DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country order by id DESC,countryname,countrycode ASC
DEBUG [main] - ==> Parameters:
DEBUG [main] - <==      Total: 183

6.2.4 去重

示例:

CountryExample example = new CountryExample();
//設定 distinct
example.setDistinct(true);
example.createCriteria().andCountrynameLike("A%");
example.or().andIdGreaterThan(100);
List<Country> countries = mapper.selectByExample(example);

日誌:

DEBUG [main] - ==>  Preparing: SELECT distinct id,countryname,countrycode FROM country WHERE ( countryname like ? ) or ( Id > ? ) ORDER BY id desc
DEBUG [main] - ==> Parameters: A%(String), 100(Integer)
DEBUG [main] - <==      Total: 95

6.2.5 設定查詢列

示例:

Example example = new Example(Country.class);
example.selectProperties("id", "countryname");
List<Country> countries = mapper.selectByExample(example);

日誌:

DEBUG [main] - ==>  Preparing: SELECT id , countryname FROM country ORDER BY id desc
DEBUG [main] - ==> Parameters:
DEBUG [main] - <==      Total: 183

    除了這裡提到的方法外,還有很多其他的方法,可以檢視 Example 原始碼進行了解。

6.3 Example.builder 方式

示例:

Example example = Example.builder(Country.class)
        .select("countryname")
        .where(Sqls.custom().andGreaterThan("id", 100))
        .orderByAsc("countrycode")
        .forUpdate()
        .build();
List<Country> countries = mapper.selectByExample(example);

日誌:

DEBUG [main] - ==>  Preparing: SELECT countryname FROM country WHERE ( id > ? ) order by countrycode Asc FOR UPDATE
DEBUG [main] - ==> Parameters: 100(Integer)
DEBUG [main] - <==      Total: 83

6.4 Weekend

使用 6.2 和 6.3 中的 Example 時,需要自己輸入屬性名,例如 "countryname",假設輸入錯誤,或者資料庫有變化,這裡很可能就會出錯,因此基於 Java 8 的方法引用是一種更安全的用法,如果你使用 Java 8,你可以試試 Weekend。

示例:

List<Country> selectByWeekendSql = mapper.selectByExample(new Example.Builder(Country.class)
        .where(WeekendSqls.<Country>custom().andLike(Country::getCountryname, "%a%")
                .andGreaterThan(Country::getCountrycode, "123"))
        .build());

日誌:

DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country WHERE ( countryname like ? and countrycode > ? )
DEBUG [main] - ==> Parameters: %a%(String), 123(String)
DEBUG [main] - <==      Total: 151

相關推薦

springboot通用mapper擴充套件通用介面Example 用法

專案中提供了大量現成的方法,這些方法可以作為擴充套件時的參考。例如 selectAll 方法。首先定義介面:@RegisterMapperpublic interface SelectAllMapper<T> {    /**     * 查詢全部結果     *

iOS開發獲取iPhone/iPad/Android 介面icon尺寸規範

注意:iOS所有圖示的圓角效果由系統生成,給到的圖示本身不能是圓角的。1. 桌面圖示 (app icon)for iPhone6 plus(@3x) : 180 x 180for iPhone 6/5s

Java抽象(abstract)類、介面(interface)的用法總結

導讀: 1、什麼是抽象類(abstract)? 2、如何定義抽象類(abstract)? 3、抽象類(abstract)的作用? 4、何為介面?介面和類的區別? 5、怎麼區分抽象類和介面? 1、抽象類的定義:         Java中宣告一個類時,可以不給出該類的所有

mybatis mapper介面以及example用法

一、mapper介面中的方法解析mapper介面中的函式及方法方法功能說明int countByExample(UserExample example) thorws SQLException按條件計數int deleteByPrimaryKey(Integer id) th

SpringBoot框架通用mapper外掛(tk.mybatis)

一.Tkmybatis的好處 Tkmybatis是在mybatis框架的基礎上提供了很多工具,讓開發更加高效。這個外掛裡面封裝好了我們需要用到的很多sql語句,不過這個外掛是通過我們去呼叫它封裝的各種方法來實現sql語句的效果。對於單表查詢不需要寫SQL語句,這樣就不用像mybatis那樣每次寫

Mapper整合擴充套件通用介面

擴充套件通用介面 專案中提供了大量現成的方法,這些方法可以作為擴充套件時的參考。 例如 selectAll 方法。 首先定義介面: @RegisterMapper public interface SelectAllMapper<T> { /**

Springboot結合mybatismybatis generator的外掛,利用tk.mybatis的通用mapper實現逆向工程。

SpringBoot結合Mybatis的generator外掛以及tk.mybatis的通用mapper實現逆向工程的生成 1.首先在資料庫中建好表。 2.然後在pom中增加mybatis和通用mapper的依賴,以及generator的外掛。 3.需要自己在u

SpringBoot整合MyBatis、PageHelper通用Mapper

之前一直用SSM框架,今天嘗試了一下將MyBatis、PageHelper和通用Mapper進行整合,所以將整合過程記錄作為後續檢視之用。 Mybatis-PageHelper的說明介紹可以點選這裡,一些配置引數與使用介紹可以點選這裡檢視,我在整合這些外掛的時

Linux SPI匯流排裝置驅動架構二:SPI通用介面

通過上一篇文章的介紹,我們知道,SPI通用介面層用於把具體SPI裝置的協議驅動和SPI控制器驅動聯接在一起,通用介面層除了為協議驅動和控制器驅動提供一系列的標準介面API,同時還為這些介面API定義了相應的資料結構,這些資料結構一部分是SPI裝置、SPI協議驅動和SPI控制

後端路一:搭建簡單伺服器(SpringBoot+Gradle實現通用Mapper

注意:本文參考網上大神寫的一個Mybtais通用框架而實現的,框架地址:http://git.oschina.net/free/Mapper2/blob/master/wiki/mapper/4.Spring4.md 本文思路主要使用SpringBoot+Mybatis+G

spring-boot集成PageHelper通用Mapper

sem r.java文件 slf4j port warn utils arraylist contex tsql 前提條件:已經集成mybatis 代碼生成步驟: 添加依賴 <dependency> <groupId>tk.mybatis

通用mapper分類實現

list集合 如果 循環 最終 font 6.4 ide 自增 架構 1 通用Mapper 1.1 通用Mapper介紹 1.1.1 架構設計 說明:使用了通用Mapper後,單表的增刪改查操作會自動的進行維護. 問題:如何才能實現數據的通用並且是動態的? 1.2

SpringBoot + Druid資料來源 Mysql資料庫 通用Mapper

springboot專案使用自己配置Druid資料來源,mysql資料庫,通用mapper外掛,pagehelper分頁, DruidConfiguration.class   import java.sql.SQLException; import javax.sql.

springboot(6)——Mybatis逆向生成及通用Mapper

一、資料庫中user表 只有id和name兩個欄位 二、新增jar包、設定逆向工程的build配置,pom.xml檔案如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave

資料新增非同步解析重新整理大資料量redis (——)(二) SpringBootCommandLineRunner介面ApplicationRunner介面

在spring boot應用中,我們可以在程式啟動之前執行任何任務。為了達到這個目的,我們需要使用CommandLineRunner或ApplicationRunner介面建立bean,spring boot會自動監測到它們。這兩個介面都有一個run()方法,在實現介面時需要覆蓋該方法,並使用@

SpringBoot筆記(三)通用mapper

mybatis的官網(https://github.com/mybatis/spring-boot-starter)提供了對springboot的支援。 1、pom三座標 <dependency> <groupId>org.mybatis.spring.boo

Springboot整合通用mapper、XML、service《spring boot學習五》

1. springmvc之mapper.xml的痛 ​ 一般情況下都是一個類寫一個xml或者說即使N個類共用一個XML,其實對於開發者的工作量也是很大的,前期倒沒有什麼,因為可以用自動生成工具來生成,但是後期,如果要新增什麼欄位或者修改欄位的話,對於我們來說真的太噁心了 ​ 所以

Linux中斷(interrupt)子系統四:驅動程式介面層 & 中斷通用邏輯層

轉載地址:https://blog.csdn.net/DroidPhone/article/details/7497787 在本系列文章的第一篇:Linux中斷(interrupt)子系統之一:中斷系統基本原理,我把通用中斷子系統分為了4個層次,其中的驅動程式介面層和中斷通用邏輯層的界限實際上不

SSM整合兩種配置方式——xmljavaConfig,新增分頁外掛pageHelper通用Mapper

Spring MVC配置 1. xml方式 web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"  

Mybatis(攔截器實現)通用mapper及全ORM實現(五)-- springboot+mybatis多資料來源設定

本篇實際上和mybatisext專案並沒有太大關係了,但在實際專案中脫離不開多個數據源,尤其是主從分離,同樣網上一些資料大同小異而且大部分並不能真正解決問題,所以單獨提出來說一下 假設我們就是要解決一個主從分離,資料來源定義在了application.properties中