![](/img/trans.png)
[英]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.