问题描述
我想从XML配置迁移到Java配置.
I want to migrate from XML configuration to Java configuration.
sqlSessionFactory.getConfiguration().setEnvironment(new Environment("development", new org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory(), getDataSouroce()));
我设法用Java配置替换了所有<environments>
部分(我已经从XML配置文件中删除了<environments>
),但是我无法摆脱:
I managed to replace all <environments>
section with Java configuration (I have removed <environments>
from XML configuration file), but I can't get rid of:
<mappers><mapper resource="mailbox/db/map/FileMapper.xml"/> </mappers>
我试图写:
但有例外:
SqlSession sqlSession = MyBatisConnectionFactory.instance.getSqlSessionFactory().openSession();
FileExample fe = new FileExample();
Criteria f = fe.createCriteria().andIdBetween(0L, 5L);
FileMapper mapper = (FileMapper) sqlSession.getMapper(FileMapper.class);
List<File> allRecords = mapper.selectByExample(fe);
// Mapped Statements collection does not contain value for mailbox.db.dao.FileMapper.selectByExample
推荐答案
我在下面的抽象映射器工厂中使用DbUtil.getInstance().getDataSource()和registerMappers()是关键点.
I am using below abstract mapper factory where DbUtil.getInstance().getDataSource() and registerMappers() are the key points.
public abstract class AbstractMapperFactory implements MapperFactory {
private ThreadLocal<SqlSessionManager> sessionManagerThreadLocal = new ThreadLocal<SqlSessionManager>();
public <T> T getMapper(Class<T> clazz) throws DaoException {
if(sessionManagerThreadLocal.get() == null) {
initialize();
}
return sessionManagerThreadLocal.get().getMapper(clazz);
}
public void closeSession() {
if(sessionManagerThreadLocal.get() != null) {
sessionManagerThreadLocal.get().close();
sessionManagerThreadLocal.remove();
}
}
private void initialize() throws DaoException {
Environment environment = new Environment("env", new ManagedTransactionFactory(), DbUtil.getInstance().getDataSource());
Configuration configuration = new Configuration(environment);
registerMappers(configuration);
sessionManagerThreadLocal.set(SqlSessionManager.newInstance(new SqlSessionFactoryBuilder().build(configuration)));
}
protected abstract void registerMappers(Configuration configuration);
}
DbUtil.getInstance().getDataSource()负责获取java.sql.DataSource实例,无论它是托管实例还是简单实例.
Where DbUtil.getInstance().getDataSource() is responsible for getting the java.sql.DataSource instance, whether it is managed or simple.
registerMappers()是一种抽象方法,子类可以使用以下代码注册其映射器:
registerMappers() is an abstract method where subclass can register their mappers using code like below:
protected void registerMappers(Configuration configuration) {
configuration.addMapper(PartMapper.class);
configuration.addMapper(StatusMapper.class);
configuration.addMapper(NoteTypeMapper.class);
configuration.addMapper(AssetTypeMapper.class);
}
这篇关于在Java中将映射器添加到myBatis配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!