Spring启动似乎无法找到mybatis映射器配置(Mapped Statements集合不包含值)

时间:2018-02-18 06:59:28

标签: java spring-boot mybatis spring-mybatis

我正在使用mybatis和spring-boot。

我已经遭受了几个小时的跟踪消息。

2018-02-18 15:25:13.774 ERROR 77556 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for org.owls.mybatis.mapper.TestMapper.selectTimestamp
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for org.owls.mybatis.mapper.TestMapper.selectTimestamp] with root cause

java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for org.owls.mybatis.mapper.TestMapper.selectTimestamp

我的源代码基于this(Spring启动项目开始)并添加了Mybatis设置。

我想mybatis无法找到映射器信息,所以我想在控制台中打印已注册的mybatis映射器列表。 (有可能吗?)

仅供参考,以下是我实施的内容。

我使用application.yml添加mybatis

mybatis:
    type-aliases-package: org.owls.mybatis.model
    type-handlers-package: org.owls.mybatis.handler
    mapper-locations: classpath:/resources/mybatis/mapper/*_mapper.xml 
    configuration:
        map-underscore-to-camel-case: true
        default-fetch-size: 100
        default-statement-timeout: 30

这是/resources/mybatis/mapper/test_mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.owls.mybatis.mapper.TestMapper">
    <select id="selectTimestamp" resultType="map">
        SELECT NOW() FROM DUAL
    </select>
</mapper>

从这里开始是Java代码。

首先,TestMapper包中的Mapper接口org.owls.mybatis.mapper

public interface TestMapper {
    @Select("SELECT NOW() FROM DUAL")
    public Map selectTimestamp() throws Exception;
}

其次,我制作了一个生成SqlSessionTemplate的服务。这是代码

@Service
public class MybatisService implements ApplicationContextAware {

    private Logger logger = Logger.getLogger(MybatisService.class);
    private ApplicationContext context;

    @Autowired
    DBService dbService;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }


    // Register a Object with a name, if not exists
    private void registerBean(String beanName, Object newBean){
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry)  context.getAutowireCapableBeanFactory();
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(newBean.getClass());
        BeanDefinition def = builder.getBeanDefinition();
        if(!registry.containsBeanDefinition(beanName)) registry.registerBeanDefinition(beanName, def);
    }


    /*
    * Managing SqlSessionFactory
    * */
    private SqlSessionFactory generateSqlSessionFactory(String dsId, DataSource ds) throws Exception {
        String beanName = dsId + "SqlSessionFactory";

        SqlSessionFactory sqlSessionFactory = null;
        try {
            Object registeredBean = context.getBean(beanName);
            logger.info("Found SqlSessionFactory bean [ " + beanName + " ]. Returns the instance");
            sqlSessionFactory = (SqlSessionFactory) registeredBean;
        } catch (NoSuchBeanDefinitionException e) {
            logger.info("Not found SqlSessionFactory bean [ " + beanName + " ]. Generate new one");
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(ds);
            sqlSessionFactory = (SqlSessionFactory) sqlSessionFactoryBean.getObject();
            registerBean(beanName, sqlSessionFactory);
        }
        return sqlSessionFactory;
    }


    /*
    * Managing SqlSessionTemplate
    * */
    private SqlSessionTemplate generateSqlSessionTemplate(String dsId, SqlSessionFactory sqlSessionFactory) throws Exception {
        String beanName = dsId + "SqlSessionTemplate";
        SqlSessionTemplate sqlSessionTemplate = null;
        try {
            Object registeredBean = context.getBean(beanName);
            logger.info("Found SqlSessionTemplate bean [ " + beanName + " ]. Returns the instance");
            sqlSessionTemplate = (SqlSessionTemplate) registeredBean;
        } catch (NoSuchBeanDefinitionException e) {
            logger.info("Not found SqlSessionTemplate bean [ " + beanName + " ]. Generate new one");
            sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
            registerBean(beanName, sqlSessionFactory);
        }
        return sqlSessionTemplate;
    }


    public SqlSessionTemplate getSqlSessionTemplate(String dsId) {
        SqlSessionTemplate template = null;
        try {
            DataSource ds = dbService.getDS(dsId);
            SqlSessionFactory sqlSessionFactory = generateSqlSessionFactory(dsId, ds);
            template = generateSqlSessionTemplate(dsId, sqlSessionFactory);
        } catch (Exception e) {
            logger.error("Failed to fetch SqlSessionFactory. returns null value ", e);
        }
        return template;
    }
}

最后,在Controller中,我将其称为...

@Controller
@RequestMapping(value = {"/test"})
public class TestController {

    @Autowired
    MybatisService mybatisService;
    private SqlSessionTemplate sqlSessionTemplate;

    private Logger logger = Logger.getLogger(TestController.class);

    @PostConstruct
    public void init(){
        sqlSessionTemplate = mybatisService.getSqlSessionTemplate("test");
    }

    @RequestMapping(value = {"getCurrentTimestamp"})
    public @ResponseBody String getCurrentTimestamp() throws Exception {

        logger.info("=== SqlSessionTemplate Info in Controller :: " + sqlSessionTemplate);

        Map<String, Object> data = (Map) sqlSessionTemplate.selectOne("org.owls.mybatis.mapper.TestMapper.selectTimestamp");
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(data);
    }
};

我认为错误信息有点模糊。 (我在设置中找不到任何错误的线索 - mapper xmlapplication.ymldb connection

感谢您的回答。 Access full source code

========================编辑#1。 19月20日=============================

我发现SqlSessionFactory Configuration根本没有任何映射器。

我可以通过以下方式打印映射器列表。 在代码中生成SqlSessionFactory ...

// FOR TEST 0219
MapperRegistry registry = sqlSessionFactory.getConfiguration().getMapperRegistry();


logger.info("=== Printing Mapper Registry starts");
registry.getMappers().forEach(mapper -> {
    logger.info("Mapper Registry :: " +  mapper.getName());
});
logger.info("=== Printing Mapper Registry ends");
// FOR TEST 0219

在我的情况下,它什么都不打印,但它能够通过MapperRegistry实例添加mapper或package。

这就是我的想法

  1. SqlSessionFactory(由ibatis提供)需要DataSource
  2. SqlSessionTemplate(由ibatis提供)是端点,需要SqlSessionFactory
  3. 总之,SqlSessionTemplate取决于取决于SqlSessionFactory的{​​{1}}。
  4. 如果是这样,我如何在使用动态数据源的项目中正确生成DataSource作为bean?

    在我的上层代码(编辑过的代码)中,我能够将mapper添加为bean,但每个SqlSession*都有相同的Mappers(重复,因为SqlSessionFactory获取包名称作为参数)

    如何将不同的地图制作器设置为对应的MapperRegistry

0 个答案:

没有答案