测试时,可快速调用 Mapper 的 Mapper Generator

项目 Gitee 地址:MapperGenerator (当前使用的是 JDK17,JDK8 的需改下 pom.xml 文件)

解决的问题:SpringBootTest 启动太慢

使用方式

假设有这样一个数据库,名为 a

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for a
-- ----------------------------
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a`  (
  `a` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `b` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `c` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of a
-- ----------------------------
INSERT INTO `a` VALUES ('1', '1', '2');
INSERT INTO `a` VALUES ('2', '1', '2');
INSERT INTO `a` VALUES ('3', '1', '3');
INSERT INTO `a` VALUES ('4', '1', '3');
INSERT INTO `a` VALUES ('5', '1', '4');
INSERT INTO `a` VALUES ('6', '1', '5');

SET FOREIGN_KEY_CHECKS = 1;

使用如下
测试时,可快速调用 Mapper 的 Mapper Generator_第1张图片

 @Test
 public void test_mapper_find_all() {
     // 获取 Mapper
     AMapper mapper = MapperGenerator.getMapper(AMapper.class);
     // 执行内容
     List<A> all = mapper.findAll();
     // 输出结果
     all.forEach(System.out::println);
 }

项目结构如下,使用前,需修改 GeneratorConstants 下的配置信息
测试时,可快速调用 Mapper 的 Mapper Generator_第2张图片

实现原理

实现原理大致如下:不使用 XML 构建 SqlSessionFactory

Configuration configuration = new Configuration(EnvironmentFactory.createEnvironment())

new SqlSessionFactoryBuilder().build(configuration);

一句话:手动配置 configuration

为 configuration 手动添加 mapper 及对应 xml

添加过程:

读取 xml 文件
xml 文件中有对应如 这样的标签,你可以通过如下的方式获取到对应 mapper interface

 XPathParser parser = new XPathParser(inputStream, true, configuration.getVariables(), new XMLMapperEntityResolver());
 String namespace = parser.evalNode("/mapper").getStringAttribute("namespace");

这样,xml 文件有了,对应的 mapper interface 也有了,就可以将它们 add 到 configuration 中了

// 1)加载 mapper interface
configuration.addMapper(aClass);

// 2)加载 xml 文件,参考 mybatis 源码:XMLConfigBuilder # mapperElement(XNode parent)
try (InputStream inputStream = Resources.getUrlAsStream(path)) {
    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, path, configuration.getSqlFragments());
    mapperParser.parse();
} catch (IOException e) {
    throw new RuntimeException(e);
}

具体感兴趣的可以看看整个项目的代码

你可能感兴趣的:(mybatis,java,mysql)