// MapperAnnotationBuilderprivate void loadXmlResource() {// Spring may not know the real resource name so we check a flag// to prevent loading again a resource twice// this flag is set at XMLMapperBuilder#bindMapperForNamespace// xml 的id "namespace:xxx.xx.xx.UserMapper"if (!configuration.isResourceLoaded("namespace:" + type.getName())) {// 加载 xmlString xmlResource = type.getName().replace('.', '/') + ".xml";// #1347InputStream inputStream = type.getResourceAsStream("/" + xmlResource);if (inputStream == null) {// Search XML mapper that is not in the module but in the classpath.try {inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);} catch (IOException e2) {// ignore, resource is not required}}if (inputStream != null) {// 解析 XMLMapperXMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());xmlParser.parse();}}}`
说明:加载 xml 部分,默认是获取 class.getName,相当于是 package 路径 +.xml
如下:
类路径 org.apache.UserMapper.class
XML 加载路径 org/apache/UserMapper.xml
@Testpublic void configRegisterMapperTest() {Configuration configuration = new Configuration();// 构建 EnvironmentEnvironment.Builder builder = new Environment.Builder("11");builder.dataSource(new UnpooledDataSource("com.mysql.jdbc.Driver","jdbc:mysql://120.78.218.163:3306/storm_sports","root","@D23d7a3df91cc42"));builder.transactionFactory(new JdbcTransactionFactory());configuration.setEnvironment(builder.build());// 添加 mapperconfiguration.addMapper(UserMapper.class);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configuration);// 开启 sqlSessionSqlSession sqlSession = factory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);// 查询UserDO userDO = userMapper.selectById(1L);sqlSession.close();System.err.println(userDO);}
说明:MyBatis 传统模式采用 mybatis-config.xml 配置,配置过程是:
<configuration>
标签内容<configuration>
标签内容// 直接操作sql,不进行预编译,获取数据:$—StatementSTATEMENT,// 预处理,参数,进行预编译,获取数据:#—–PreparedStatement:默认PREPARED,// 执行存储过程————CallableStatementCALLABLE