麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > Java > 正文

淺談MyBatis通用Mapper實現原理

2024-07-14 08:42:37
字體:
來源:轉載
供稿:網友

本文會先介紹通用 Mapper 的簡單原理,然后使用最簡單的代碼來實現這個過程。

基本原理

通用 Mapper 提供了一些通用的方法,這些通用方法是以接口的形式提供的,例如。

public interface SelectMapper<T> {  /**   * 根據實體中的屬性值進行查詢,查詢條件使用等號   */  @SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")  List<T> select(T record);}

接口和方法都使用了泛型,使用該通用方法的接口需要指定泛型的類型。通過 Java 反射可以很容易得到接口泛型的類型信息,代碼如下。

Type[] types = mapperClass.getGenericInterfaces();Class<?> entityClass = null;for (Type type : types) {  if (type instanceof ParameterizedType) {    ParameterizedType t = (ParameterizedType) type;    //判斷父接口是否為 SelectMapper.class    if (t.getRawType() == SelectMapper.class) {      //得到泛型類型      entityClass = (Class<?>) t.getActualTypeArguments()[0];      break;    }  }}

實體類中添加的 JPA 注解只是一種映射實體和數據庫表關系的手段,通過一些默認規則或者自定義注解也很容易設置這種關系,獲取實體和表的對應關系后,就可以根據通用接口方法定義的功能來生成和 XML 中一樣的 SQL 代碼。動態生成 XML 樣式代碼的方式有很多,最簡單的方式就是純 Java 代碼拼字符串,通用 Mapper 為了盡可能的少的依賴選擇了這種方式。如果使用模板(如 FreeMarker,Velocity 和 beetl 等模板引擎)實現,自由度會更高,也能方便開發人員調整。

在 MyBatis 中,每一個方法(注解或 XML 方式)經過處理后,最終會構造成 MappedStatement 實例,這個對象包含了方法id(namespace+id)、結果映射、緩存配置、SqlSource 等信息,和 SQL 關系最緊密的是其中的 SqlSource,MyBatis 最終執行的 SQL 時就是通過這個接口的 getBoundSql 方法獲取的。

在 MyBatis 中,使用@SelectProvider 這種方式定義的方法,最終會構造成 ProviderSqlSource,ProviderSqlSource 是一種處于中間的 SqlSource,它本身不能作為最終執行時使用的 SqlSource,但是他會根據指定方法返回的 SQL 去構造一個可用于最后執行的 StaticSqlSource,StaticSqlSource的特點就是靜態 SQL,支持在 SQL 中使用#{param} 方式的參數,但是不支持 <if>,<where> 等標簽。

為了能根據實體類動態生成支持動態 SQL 的方法,通用 Mapper 從這里入手,利用ProviderSqlSource 可以生成正常的 MappedStatement,可以直接利用 MyBatis 各種配置和命名空間的特點(這是通用 Mapper 選擇這種方式的主要原因)。在生成 MappedStatement 后,“過河拆橋” 般的利用完就把 ProviderSqlSource 替換掉了,正常情況下,ProviderSqlSource 根本就沒有執行的機會。在通用 Mapper 定義的實現方法中,提供了 MappedStatement 作為參數,有了這個參數,我們就可以根據 ms 的 id(規范情況下是 接口名.方法名)得到接口,通過接口的泛型可以獲取實體類(entityClass),根據實體和表的關系我們可以拼出 XML 方式的動態 SQL,一個簡單的方法如下。

/** * 查詢全部結果 * * @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();}

拼出的 XML 形式的動態 SQL,使用 MyBatis 的 XMLLanguageDriver 中的 createSqlSource 方法可以生成 SqlSource。然后使用反射用新的 SqlSource 替換ProviderSqlSource 即可,如下代碼。

/** * 重新設置SqlSource * * @param ms * @param sqlSource */protected void setSqlSource(MappedStatement ms, SqlSource sqlSource) {  MetaObject msObject = SystemMetaObject.forObject(ms);  msObject.setValue("sqlSource", sqlSource);}

MetaObject 是MyBatis 中很有用的工具類,MyBatis 的結果映射就是靠這種方式實現的。反射信息使用的 DefaultReflectorFactory,這個類會緩存反射信息,因此 MyBatis 的結果映射的效率很高。

到這里核心的內容都已經說完了,雖然知道怎么去替換 SqlSource了,但是!什么時候去替換呢?

這一直都是一個難題,如果不大量重寫 MyBatis 的代碼很難萬無一失的完成這個任務。通用 Mapper 并沒有去大量重寫,主要是考慮到以后的升級,也因此在某些特殊情況下,通用 Mapper 的方法會在沒有被替換的情況下被調用,這個問題在將來的 MyBatis 3.5.x 版本中會以更友好的方式解決(目前的 ProviderSqlSource 已經比以前能實現更多的東西,后面會講)。

針對不同的運行環境,需要用不同的方式去替換。當使用純 MyBatis (沒有Spring)方式運行時,替換很簡單,因為會在系統中初始化 SqlSessionFactory,可以初始化的時候進行替換,這個時候也不會出現前面提到的問題。替換的方式也很簡單,通過 SqlSessionFactory 可以得到 SqlSession,然后就能得到 Configuration,通過 configuration.getMappedStatements() 就能得到所有的 MappedStatement,循環判斷其中的方法是否為通用接口提供的方法,如果是就按照前面的方式替換就可以了。

在使用 Spring 的情況下,以繼承的方式重寫了 MapperScannerConfigurer 和 MapperFactoryBean,在 Spring 調用 checkDaoConfig 的時候對 SqlSource 進行替換。在使用 Spring Boot 時,提供的 mapper-starter 中,直接注入 List<SqlSessionFactory> sqlSessionFactoryList 進行替換。

下面我們按照這個思路,以最簡練的代碼,實現一個通用方法。

實現一個簡單的通用 Mapper

1. 定義通用接口方法

public interface BaseMapper<T> {  @SelectProvider(type = SelectMethodProvider.class, method = "select")  List<T> select(T entity);}

這里定義了一個簡單的 select 方法,這個方法判斷參數中的屬性是否為空,不為空的字段會作為查詢條件進行查詢,下面是對應的 Provider。

public class SelectMethodProvider {  public String select(Object params) {    return "什么都不是!";  }}

這里的 Provider 不會最終執行,只是為了在初始化時可以生成對應的 MappedStatement。

2. 替換 SqlSource

下面代碼為了簡單,都指定的 BaseMapper 接口,并且沒有特別的校驗。

public class SimpleMapperHelper {  public static final XMLLanguageDriver XML_LANGUAGE_DRIVER      = new XMLLanguageDriver();  /**   * 獲取泛型類型   */  public static Class getEntityClass(Class<?> mapperClass){    Type[] types = mapperClass.getGenericInterfaces();    Class<?> entityClass = null;    for (Type type : types) {      if (type instanceof ParameterizedType) {        ParameterizedType t = (ParameterizedType) type;        //判斷父接口是否為 BaseMapper.class        if (t.getRawType() == BaseMapper.class) {          //得到泛型類型          entityClass = (Class<?>) t.getActualTypeArguments()[0];          break;        }      }    }    return entityClass;  }  /**   * 替換 SqlSource   */  public static void changeMs(MappedStatement ms) throws Exception {    String msId = ms.getId();    //標準msId為 包名.接口名.方法名    int lastIndex = msId.lastIndexOf(".");    String methodName = msId.substring(lastIndex + 1);    String interfaceName = msId.substring(0, lastIndex);    Class<?> mapperClass = Class.forName(interfaceName);    //判斷是否繼承了通用接口    if(BaseMapper.class.isAssignableFrom(mapperClass)){      //判斷當前方法是否為通用 select 方法      if (methodName.equals("select")) {        Class entityClass = getEntityClass(mapperClass);        //必須使用<script>標簽包裹代碼        StringBuffer sqlBuilder = new StringBuffer("<script>");        //簡單使用類名作為包名        sqlBuilder.append("select * from ").append(entityClass.getSimpleName());        Field[] fields = entityClass.getDeclaredFields();        sqlBuilder.append(" <where> ");        for (Field field : fields) {          sqlBuilder.append("<if test=/"")              .append(field.getName()).append("!=null/">");          //字段名直接作為列名          sqlBuilder.append(" and ").append(field.getName())               .append(" = #{").append(field.getName()).append("}");          sqlBuilder.append("</if>");        }        sqlBuilder.append("</where>");        sqlBuilder.append("</script>");        //解析 sqlSource        SqlSource sqlSource = XML_LANGUAGE_DRIVER.createSqlSource(            ms.getConfiguration(), sqlBuilder.toString(), entityClass);        //替換        MetaObject msObject = SystemMetaObject.forObject(ms);        msObject.setValue("sqlSource", sqlSource);      }    }  }}

changeMs 方法簡單的從 msId 開始,獲取接口和實體信息,通過反射回去字段信息,使用 <if> 標簽動態判斷屬性值,這里的寫法和 XML 中一樣,使用 XMLLanguageDriver 處理時需要在外面包上 <script> 標簽。生成 SqlSource 后,通過反射替換了原值。

3. 測試

針對上面代碼,提供一個 country 表和對應的各種類。

實體類。

public class Country { private Long  id; private String countryname; private String countrycode; //省略 getter,setter} 

Mapper 接口。

public interface CountryMapper extends BaseMapper<Country> {}

啟動 MyBatis 的公共類。

public class SqlSessionHelper {  private static SqlSessionFactory sqlSessionFactory;  static {    try {      Reader reader = Resources.getResourceAsReader("mybatis-config.xml");      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);      reader.close();      //創建數據庫      SqlSession session = null;      try {        session = sqlSessionFactory.openSession();        Connection conn = session.getConnection();        reader = Resources.getResourceAsReader("hsqldb.sql");        ScriptRunner runner = new ScriptRunner(conn);        runner.setLogWriter(null);        runner.runScript(reader);        reader.close();      } finally {        if (session != null) {          session.close();        }      }    } catch (IOException ignore) {      ignore.printStackTrace();    }  }  public static SqlSession getSqlSession() {    return sqlSessionFactory.openSession();  }}

 配置文件。

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <environments default="development">  <environment id="development">   <transactionManager type="JDBC">    <property name="" value=""/>   </transactionManager>   <dataSource type="UNPOOLED">    <property name="driver" value="org.hsqldb.jdbcDriver"/>    <property name="url" value="jdbc:hsqldb:mem:basetest"/>    <property name="username" value="sa"/>   </dataSource>  </environment> </environments> <mappers>  <package name="tk.mybatis.simple.mapper"/> </mappers></configuration>

初始化sql。

drop table country if exists;create table country ( id integer, countryname varchar(32), countrycode varchar(2));insert into country (id, countryname, countrycode) values(1,'Angola','AO');insert into country (id, countryname, countrycode) values(23,'Botswana','BW');-- 省略部分insert into country (id, countryname, countrycode) values(34,'Chile','CL');insert into country (id, countryname, countrycode) values(35,'China','CN');insert into country (id, countryname, countrycode) values(36,'Colombia','CO');

測試代碼。

public class SimpleTest {  public static void main(String[] args) throws Exception {    SqlSession sqlSession = SqlSessionHelper.getSqlSession();    Configuration configuration = sqlSession.getConfiguration();    HashSet<MappedStatement> mappedStatements        = new HashSet<MappedStatement>(configuration.getMappedStatements());    //如果注釋下面替換步驟就會出錯    for (MappedStatement ms : mappedStatements) {      SimpleMapperHelper.changeMs(ms);    }    //替換后執行該方法    CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);    Country query = new Country();    //可以修改條件或者注釋條件查詢全部    query.setCountrycode("CN");    List<Country> countryList = mapper.select(query);    for (Country country : countryList) {      System.out.printf("%s - %s/n",          country.getCountryname(),          country.getCountrycode());    }    sqlSession.close();  }}

通過簡化版的處理過程應該可以和前面的內容聯系起來,從而理解通用 Mapper 的簡單處理過程。

完整代碼下載:simple-mapper.rar

最新的 ProviderSqlSource

早期的 ProviderSqlSource 有個缺點就是定義的方法要么沒有參數,要么只能是 Object parameterObject 參數,這個參數最終的形式在開發時也不容易一次寫對,因為不同形式的接口的參數會被 MyBatis 處理成不同的形式,可以參考 深入了解MyBatis參數。由于沒有提供接口和類型相關的參數,因此無法根據類型實現通用的方法。

在最新的 3.4.5 版本中,ProviderSqlSource 增加了一個額外可選的 ProviderContext 參數,這個類如下。

/** * The context object for sql provider method. * * @author Kazuki Shimizu * @since 3.4.5 */public final class ProviderContext { private final Class<?> mapperType; private final Method mapperMethod; /**  * Constructor.  *  * @param mapperType A mapper interface type that specified provider  * @param mapperMethod A mapper method that specified provider  */ ProviderContext(Class<?> mapperType, Method mapperMethod) {  this.mapperType = mapperType;  this.mapperMethod = mapperMethod; } /**  * Get a mapper interface type that specified provider.  *  * @return A mapper interface type that specified provider  */ public Class<?> getMapperType() {  return mapperType; } /**  * Get a mapper method that specified provider.  *  * @return A mapper method that specified provider  */ public Method getMapperMethod() {  return mapperMethod; }}

有了這個參數后,就能獲取到接口和當前執行的方法信息,因此我們已經可以實現通用方法了。

下面是一個官方測試中的簡單例子,定義的通用接口如下。

public interface BaseMapper<T> { @SelectProvider(type= OurSqlBuilder.class, method= "buildSelectByIdProviderContextOnly") @ContainsLogicalDelete T selectById(Integer id); @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface ContainsLogicalDelete {  boolean value() default false; } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface Meta {  String tableName(); }}

接口定義了一個簡單的根據 id 查詢的方法,定義了一個邏輯刪除的注解、還有一個表名的元注解。

下面是 方法的實現。

public String buildSelectByIdProviderContextOnly(ProviderContext context) { //獲取方法上的邏輯刪除注解 final boolean containsLogicalDelete = context.getMapperMethod().      getAnnotation(BaseMapper.ContainsLogicalDelete.class) != null; //獲取接口上的元注解(不是實體) final String tableName = context.getMapperType().      getAnnotation(BaseMapper.Meta.class).tableName(); return new SQL(){{  SELECT("*");  FROM(tableName);  WHERE("id = #{id}");  if (!containsLogicalDelete){   WHERE("logical_delete = ${Constants.LOGICAL_DELETE_OFF}");  } }}.toString();}

這里相比之前,可以獲取到更多的信息,SQL 也不只是固定表的查詢,可以根據 @Meta 注解制定方法查詢的表名,和原來一樣的是,最終還是返回一個簡單的 SQL 字符串,仍然不支持動態 SQL 的標簽。

下面是實現的接口。

@BaseMapper.Meta(tableName = "users")public interface Mapper extends BaseMapper<User> {}

上面實現的方法中,注解從接口獲取的,因此這里也是在 Mapper 上配置的 Meta 接口。

按照前面通用 Mapper 中的介紹,在實現方法中是可以獲取 User 類型的,因此如果把注解定義在實體類上也是可行的。

現在看起來已經很不錯了,但是還不支持動態 SQL,還不能緩存根據 SQL 生成的 SqlSource,因此每次執行都需要執行方法去生成 SqlSource,仍然還有改進的地方,為了解決這個問題,我提交了兩個PR #1111,#1120,目前還在討論階段,真正實現可能要到 3.5.0 版本。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 91丝袜| 最近高清无吗免费看 | 国产亚洲精彩视频 | 超碰一区 | 成人在线视频在线观看 | 亚洲第一成av人网站懂色 | 一级做a爰片性色毛片2021 | 亚洲国产成人久久一区www妖精 | 国产成人自拍视频在线 | 免费观看黄色一级视频 | omofun 动漫在线观看 | 国产在线观看91精品 | 日本在线播放一区 | 一本一道久久久a久久久精品91 | 91丨九色丨国产在线观看 | 成人在线视频在线观看 | 国产88久久久国产精品免费二区 | 羞羞视频免费入口网站 | 国产精品久久久久久久久久东京 | 欧美亚洲黄色片 | 深夜视频在线 | 亚洲精品3 | 精品亚洲夜色av98在线观看 | 欧美精品亚洲人成在线观看 | 一区国产在线观看 | a视频在线免费观看 | av在线成人| 国产精品久久久久影院老司 | 蜜桃视频观看麻豆 | chinese hd xxxx tube| 欧美另类69xxxxx 视频 | 深夜福利久久久 | 视频一区二区不卡 | 污黄视频在线观看 | 国产精品av久久久久久网址 | 国产一级毛片高清视频完整版 | www.精品一区 | 久久久中文 | 国产精品一区二区三区在线播放 | 久久99精品久久久久久秒播放器 | 成片免费观看视频大全 |