[英]myBatis xml mapper filer in use with Java interface - dynamic SQL query
[英]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.