在Java中将mapper添加到myBatis配置中

时间:2012-03-16 13:51:47

标签: java mybatis

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

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

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

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

我试着写:

  

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

但也有例外:

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

1 个答案:

答案 0 :(得分:2)

我在抽象映射器工厂下面使用,其中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);
}