簡體   English   中英

在java代碼中myBatis的配置中添加xml映射器,路徑不同於接口一

[英]Add xml mapper to the configuration of myBatis in the java code with path different than the interface one

我使用 java 代碼中定義的環境和數據源在 java 代碼中初始化了我的 SqlSessionFactory,如下所示:

TransactionFactory trxFactory = new JdbcTransactionFactory();
Environment env = new Environment("development", trxFactory, dataSource);
Configuration config = new Configuration(env);
config.setJdbcTypeForNull(JdbcType.NULL);
TypeAliasRegistry aliases = config.getTypeAliasRegistry();
aliases.registerAlias("XXXAttempt", XXXAttemptDao.class);
config.addMapper(XXXAttemptMapper.class);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);

我的問題是我需要在這里添加我的 xml 映射器,但我不能:我嘗試使用:

config.addMappers("config/mybatis/xxx/*.xml");

config.addMappers("config/mybatis/xxx/*.xml");

沒有運氣。 注意 config.addMapper 只接受 java class

唯一可行的方法是將 xml 文件移動到相同的 package 中,就像接口示例一樣( 參考):

config/com/example/mappers/XXXAttemptMapper.xml

但我需要的是與其他項目保持一致,並將 xml 文件放在以下路徑中:

config/myBatis/myDb/XXXAttemptMapper.xml

如何在上述位置添加我的 xml 文件的路徑?

這在 mybatis 中沒有開箱即用。 映射器接口和映射器 xml 文件之間的實際關系在MapperAnnotationBuilder class 中硬編碼

String xmlResource = type.getName().replace('.', '/') + ".xml";

並且沒有內置的方法可以覆蓋它。 為了改變這一點,您需要實現自己的MapperAnnotationBuilder等效項(您可以繼承其大部分功能,但需要覆蓋parse方法以更改調用將替換loadXmlResource的方法):

class MyMapperAnnotationBuilder extends MapperAnnotationBuilder {
  public void parse() {
    String resource = type.toString();
    if (!configuration.isResourceLoaded(resource)) {
      loadXmlResourceFromCustomPlace();
      // ... continue as MapperAnnotationBuilder.parse method
    }
  }
  void private loadXmlResourceFromCustomPlace() {
    // this should be similar to MapperAnnotationBuilder.loadXmlResource
    // but load resource from some other place
  }
}

現在您需要在自己的 class 實現中使用MyMapperAnnotationBuilder ,類似於org.apache.ibatis.binding.MapperRegistry (假設您將其MyMapperRegister )。 您需要從它繼承並覆蓋addMapper(Class<T> type)方法才能使用MyMapperAnnotationBuilder

最后一步是在Configuration中使用您的映射器注冊表實現。 無法在外部設置它,因此您需要從Configuration繼承並使用您的映射器注冊表:

class MyConfiguration extends Configuration {
  public MyConfiguration{Environment environment) {
    super(environment);
    this.mapperRegistry = new MyMapperRegister(this);
  }

在此之后,您使用MyConfiguration與使用Configuration配置 mybatis 的方式相同,它將從 MyMapperAnnotationBuilder.loadXmlResourceFromCustomPlace 中實現的邏輯定義的位置加載MyMapperAnnotationBuilder.loadXmlResourceFromCustomPlace映射器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM