gpt4 book ai didi

java - 在 Java 中将映射器添加到 myBatis 配置中

转载 作者:行者123 更新时间:2023-11-30 04:51:30 25 4
gpt4 key购买 nike

我想从 XML 配置迁移到 Java 配置。

sqlSessionFactory.getConfiguration().setEnvironment(new Environment("development", new org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory(), getDataSouroce()));

我设法替换了所有 <environments> Java 配置部分(我已从 XML 配置文件中删除 <environments>),但我无法删除:

 <mappers><mapper resource="mailbox/db/map/FileMapper.xml"/> </mappers>

我尝试写:

sqlSessionFactory.getConfiguration().addMapper(FileMapper.class);

但也有异常(exception):

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() 是关键点。

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 实例,无论它是托管的还是简单的。

registerMappers() 是一个抽象方法,子类可以使用如下代码注册其映射器:

protected void registerMappers(Configuration configuration) {
configuration.addMapper(PartMapper.class);
configuration.addMapper(StatusMapper.class);
configuration.addMapper(NoteTypeMapper.class);
configuration.addMapper(AssetTypeMapper.class);
}

关于java - 在 Java 中将映射器添加到 myBatis 配置中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9738480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com