Fluent-Mybatis 初体验

##1. Fluent-Mybatis 是什么?

官方:FluentMybatis: 基于mybatis但青出于蓝

No XML, No Mapper, No If else, No String魔法值编码
只需Entity就实现强大的FluentAPI: 支持分页, 嵌套查询, AND OR组合, 聚合函数…

摘自官方:
在这里插入图片描述
在这里插入图片描述

这里基本可以知道fluent-mybatis的一个特性。而下面可以开始写一个小dome

2. fluent-mybatis

2.1 引入相关依赖

 <!-- 引入fluent-mybatis 运行依赖包, scope为compile -->
 <dependency>
     <groupId>com.github.atool</groupId>
     <artifactId>fluent-mybatis</artifactId>
     <version>1.6.8</version>
 </dependency>
 
 <!-- 引入fluent-mybatis-processor, scope设置为provider 编译需要,运行时不需要 -->
 <dependency>
     <groupId>com.github.atool</groupId>
     <artifactId>fluent-mybatis-processor</artifactId>
     <version>1.6.8</version>
 </dependency>
 
<!--mybatis-->
 <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.3.1</version>
 </dependency>

 <!-- MySQL -->
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.28</version>
 </dependency>

2.2 实体类生成工具

这个代码官方有提供

# 建表语句
-- ----------------------------
-- Table structure for hello_world
-- ----------------------------
DROP TABLE IF EXISTS `hello_world`;
CREATE TABLE `hello_world`  (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `say_hello` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `your_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gmt_created` datetime NULL DEFAULT NULL COMMENT '创建时间',
  `gmt_modified` datetime NULL DEFAULT NULL COMMENT '更新时间',
  `is_deleted` tinyint(2) NULL DEFAULT 0 COMMENT '是否逻辑删除',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1682264004749754369 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '简单演示表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for hello_world_custom
-- ----------------------------
DROP TABLE IF EXISTS `hello_world_custom`;
CREATE TABLE `hello_world_custom`  (
  `id` bigint(20) NOT NULL,
  `say_hello` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `your_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gmt_created` datetime NULL DEFAULT NULL COMMENT '创建时间',
  `gmt_modified` datetime NULL DEFAULT NULL COMMENT '更新时间',
  `is_deleted` tinyint(2) NULL DEFAULT 0 COMMENT '是否逻辑删除',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '简单演示表' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
public class EntityGenerator {
    public static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis?useUnicode=true&characterEncoding=utf8";

    public static void main(String[] args) throws Exception {
        FileGenerator.build(Empty.class);
    }

    @Tables(
            // 设置数据库连接信息
            url = url, username = "username", password = "password",
            // 设置entity类生成src目录, 相对于 user.dir
            srcDir = "src/main/java",
            // 设置entity类的package值
            basePack = "com.jerry.fluentmybatisdome",
            // 设置dao接口和实现的src目录, 相对于 user.dir
            daoDir = "src/main/java",
            // 设置哪些表要生成Entity文件
            tables = {@Table(value = {"hello_world_custom"})}
    )
    static class Empty {
    }
}

2.3 通过实体类编译 编译后得到下图结构:

在这里插入图片描述

2.4 mysql配置、mybatis日志配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/fluent_mybatis?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&rewriteBatchedStatements=true
    username: root
    password: '123456'
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2.5 新建测试类进行简单的测试

@SpringBootTest
public class HelloWordTests {
	@Test
    void insertOne() {
        int result = helloWorldMapper.insert(new HelloWorldEntity()
                .setYourName("jerry")
                .setSayHello("jerry say hello")
        );
        System.out.println(result);
    }    
    
    @Test
    void selectOne() {
        HelloWorldEntity helloWorldEntity = helloWorldMapper.findOne(new HelloWorldQuery()
                .where
                .yourName().eq("jerry")
                .end()
        );
        System.out.println(helloWorldEntity);
    }
}

2.6 有业务需求需要自己写SQL的

按照mybatis的方式去写mapper即可

2.6.1 需要注册sqlSessionFactoryBean

@SpringBootApplication
@MapperScan("com.jerry.fluentmybatisdome.mapper")
public class FluentMybatisDomeApplication {

    public static void main(String[] args) {
        SpringApplication.run(FluentMybatisDomeApplication.class, args);
    }

    @Configuration
    class MybatisConfig {
        @Bean
        public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            bean.setMapperLocations(resolver.getResources("classpath*:mapper/**/*.xml"));
            return bean;
        }

        @Bean
        public MapperFactory mapperFactory() {
            return new MapperFactory();
        }
    }
}

2.6.2 测试类

@SpringBootTest(classes = FluentMybatisDomeApplication.class)
public class HelloWordCustomTests {

    @Autowired
    private CustomMapper customInsert;

    @Qualifier("helloWorldCustomMapper")
    @Autowired
    private HelloWorldCustomMapper helloWorldCustomMapper;


    // 自定义方法
    @Test
    void customInsert() {
        Snowflake snowflake = new Snowflake();
        HelloWorldCustomEntity helloWorldCustomEntity = new HelloWorldCustomEntity()
                .setId(snowflake.nextId())
                .setSayHello("custom entity say hello")
                .setYourName("custom")
                .setGmtCreated(new Date())
                .setIsDeleted(0);

        int result = customInsert.customInsert(helloWorldCustomEntity);
        System.out.println(result);
    }

    // fluent-mybatis 自带
    @Test
    void insert() {
        Snowflake snowflake = new Snowflake();

        // insertWithPk是使用自定义主键
        int result = helloWorldCustomMapper.insertWithPk(new HelloWorldCustomEntity()
                .setId(snowflake.nextId())
                .setSayHello("fluent-mybatis say hello")
                .setYourName("fluent-mybatis")
                .setGmtCreated(new Date())
                .setIsDeleted(0)
        );
        System.out.println(result);
    }
}

3. 基本就可以实现ORM的基本操作了

好不好用 能不能用 ?
文档不是最新的 最近更新是一年前 目前用的人还是不多 出现问题了网上找不到相关的问题

dome完整代码

Fluent-Mybatis Gitee官方仓库

Fluent-Mybatis 官方文档


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值