在使用SqlSessionFactory创建会话访问数据库时,会出现IllegalArgumentException(非法参数异常),该错误表示configuration中的mappedStatements并没有想要获取SQL映射的值。
//获取构建器
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//解析XML,构建会话工厂
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(ExecutorTest.class.getResourceAsStream("/mybatis-config.xml"));
Configuration configuration = factory.getConfiguration();
JdbcTransaction jdbcTransaction = new JdbcTransaction(factory.openSession().getConnection());
//获取SQL映射
MappedStatement mappedStatement = configuration.getMappedStatement("mybatis.mapper.UserMapper.selectById");
解决方案
- 检查大小写是否有问题!
/* 该方法是从mappedStatements中获取到相对应的MapperStatement,
而mappedStatements在创建SqlSessionFactory时从配置文件中的映射器所对应的Mapper文件中读取的
*/
public MappedStatement getMappedStatement(String id) {
return this.getMappedStatement(id, true);
}
- 查看myabtis-config.xml中读取的mapper包的路径是否正确
/*
可查看官网 https://mybatis.org/mybatis-3/zh/configuration.html 其中的映射器(mappers)
*/
<mappers>
<package name="mybatis.mapper"/>
</mappers>
在mybatis.mapper这个包下检查是否有相对应的执行方法
public interface UserMapper {
@Select({" select * from users where id=#{1}"})
User selectById(Integer id);
}