Mybatis零xml使用以及避坑指南

结构:
在这里插入图片描述
config层中MybatisConfig是一个单例,配置并生成sqlSessionFactory。

public class MybatisConfig {
    
    
    private static  SqlSessionFactory  sqlSessionFactory;

    private MybatisConfig() {
    
    
    }

    static  {
    
    
        /*数据源*/
        DataSource dataSource = new PooledDataSource(
                "com.mysql.jdbc.Driver",
                "jdbc:mysql://localhost:3306/Jan_test_learn",
                "root",
                ""
        );
        /*事务*/
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        /*环境*/
        Environment environment = new Environment("test", transactionFactory, dataSource);
        /*配置*/
        Configuration configuration = new Configuration(environment);
        /*mapper映射*/
        configuration.addMappers("org.example.dao");
        /*创建sqlSessionFactory*/
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }

    public static SqlSessionFactory getSqlSessionFactory() {
    
    
        return sqlSessionFactory;
    }
}

dao层写了一个简单的查询

public interface StuMapper {
    
    
    /**
     * 根据id查询学生姓名
     * @param id
     * @return
     */
    @Select(value = "select name from stu where id=#{id}")
     String selectName(int id);
}

主方法APP

public class App {
    
    
    public static void main(String[] args) {
    
    
        SqlSessionFactory sqlSessionFactory = MybatisConfig.getSqlSessionFactory();
        /*创建SqlSession,线程不安全的*/
        SqlSession sqlSession = sqlSessionFactory.openSession();
        /*获取mapper实例*/
        StuMapper stuMapper = sqlSession.getMapper(StuMapper.class);
        /*执行sql*/
        String name = stuMapper.selectName(21);
        /*打印结果*/
        System.out.println(name);
    }
}

避坑:

问题1:xxxis not known to the MapperRegistry在这里插入图片描述
排查打断点:
step1
在这里插入图片描述
step2
在这里插入图片描述
关键代码在这里
在这里插入图片描述
进入find方法
在这里插入图片描述
注意看这里,child size是0,大概知道问题出在哪里了。
在这里插入图片描述
返回上层方法,这里调用iterator,
在这里插入图片描述
这里粗略分析是这样,用户自己传进来一个包名,进过find方法找出其子类,addMappers方法会把这些全路径的包名保存在一个名教knownMappers的 hashMap中,获取mapper时则会在这个map中获取包名。以上分析为空,所以报错。
在这里插入图片描述
我这边怕他找不到,还特意把路径写到底了

        configuration.addMappers("org.example.StuMapperNew");
改成
        configuration.addMappers("org.example");

成功解决,导致问题的原因是在find方法里面会找子类,这里路径已经到底了,没有子类,所以size是0

问题2: Unable to load authentication plugin 'caching_sha2_password'.

在这里插入图片描述
问题解决方案:
在这里插入图片描述
看看我的版本
在这里插入图片描述
果然,改成一致。
在这里插入图片描述
跑一下
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Logicr/article/details/110050997