美文网首页
14 学习 flunet mybatis

14 学习 flunet mybatis

作者: 滔滔逐浪 | 来源:发表于2023-07-30 11:13 被阅读0次

https://gitee.com/fluent-mybatis/fluent-mybatis/wikis/fluent%20mybatis%E7%89%B9%E6%80%A7%E6%80%BB%E8%A7%88

image.png

引言
java中常用的orm框架主要是mybatis,hibername,jpa等框架。国内又以Mybatis用 的多,基于mybatis上的增强框架,又有了mybatisPlus和tk mybatis,今天我们介绍一个新的mybatis增强框架fluent mybatis,那既然JDBC---->mybatis或者Mybatis plus无疑简化了开发者的工作。
初识 Fluent Mybatis
Fluent MyBatis是一个MyBatis的增强工具,他只做了mybatis的语法糖封装,没有对mybatis做任何修改,通过编译手段,提供了一系列辅助类来帮助开发简化开发,提高效率。
FluentMybatis原理


image.png

入门初体验:

初始化SpringBoot 项目
设置项目依赖
1,springboot : 基于springboot 开发,肯定是必须的

  1. lombok:省略get,set.toString 代码的神器
    3,mysql-connector-java 数据库驱动
    4,fluent_mybatis: fluent-mybatis运行时的依赖
    5,fluent-mybatis-processor: fluent-mybatis 编译时的依赖
    6,fluent-mybatis-generator: fluent-mybatis 代码生成依赖
    7, 测试依赖的jar包: spring-test,junit '
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.taotao</groupId>
    <artifactId>fluent-mybatis-docs</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fluent-mybatis-docs</name>
    <description>fluent-mybatis-docs</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.12.RELEASE</spring-boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--应用项目依赖: lombok, spring, mysql等-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- 引入fluent-mybatis 运行依赖包, scope为compile -->
        <dependency>
            <groupId>com.github.atool</groupId>
            <artifactId>fluent-mybatis</artifactId>
            <version>1.9.9</version>
        </dependency>
        <!-- 引入fluent-mybatis-processor, scope设置为provider 编译需要,运行时不需要 -->
        <dependency>
            <groupId>com.github.atool</groupId>
            <artifactId>fluent-mybatis-processor</artifactId>
            <scope>provided</scope>
            <version>1.9.9</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>com.taotao.fluentmybatisdocs.FluentMybatisDocsApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

yml配置:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root


实例脚本

create database if not exists fluent_mybatis;
drop table if exists hello_world;
create table hello_world
(
    id           bigint unsigned auto_increment primary key,
    say_hello    varchar(100) null,
    your_name    varchar(100) null,
    gmt_created   datetime   DEFAULT NULL COMMENT '创建时间',
    gmt_modified datetime   DEFAULT NULL COMMENT '更新时间',
    is_deleted   tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除'
) ENGINE = InnoDB
  CHARACTER SET = utf8 comment '简单演示表';

创建实体类

可以手工创建Entity类,或者任何手段创建的Entity类,然后加上注解

在Entity类上加上 @FluentMybatis注解
在主键字段加 @TableId注解
在一般字段加 @TableField注解

这里直接使用fluent mybatis提供的工具类生成代码

package com.taotao.fluentmybatisdocs.config;

import cn.org.atool.generator.FileGenerator;
import cn.org.atool.generator.annotation.Table;
import cn.org.atool.generator.annotation.Tables;
import org.junit.Test;

/**
 * @program: fluent-mybatis-docs
 * @ClassName EntityGeneratorDemo
 * @description:
 * @author: wangjin
 * @create: 2023-07-28 10:32
 * @Version 1.0
 **/
public class EntityGeneratorDemo {
    // 数据源 url
    static final String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
    // 数据库用户名
    static final String username = "root";
    // 数据库密码
    static final String password = "root";

    @Test
    public void generate() throws Exception {
        // 引用配置类,build方法允许有多个配置类
        FileGenerator.build(Empty.class);
    }

    @Tables(
            // 设置数据库连接信息
            url = url, username = username, password = password,
            // 设置entity类生成src目录, 相对于 user.dir
            srcDir = "src/main/java",
            // 设置entity类的package值
            basePack = "com.taotao.fluentmybatisdocs",
            // 设置dao接口和实现的src目录, 相对于 user.dir
            daoDir = "src/main/java",
            // 设置哪些表要生成Entity文件
            /** 如果表定义记录创建,记录修改,逻辑删除字段 **/
            gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",
            /** 需要生成文件的表 **/
            tables = @Table(value = {"your_table"})


    )
    static class Empty { //类名随便取, 只是配置定义的一个载体
    }
}

    

这里有三个特殊字段
1.gmt_create,记录时间,会设置记录插入的默认值,对应生成的entity字段注解 @TableField(insert="now()")
2,gmt_modified 记录最后更新时间,会设置记录插入和更新默认值,对应生成代码Entity字段上注解 @TableField(insert="now()", update="now()")
3.is_deleted, 记录逻辑删除标识,字段类型为Boolean,且设置记录插入的默认值,对应注解 @TableField(insert="0")
执行生成代码main函数,在工程内部main/src/java目录下产出entity,DaoIntf,DaoImpl文件, 观察YourEntity的主键 id, gmt_create, gmt_modified, is_deleted这几个字段的注解

package com.taotao.fluentmybatisdocs.entity;

import cn.org.atool.fluent.mybatis.annotation.FluentMybatis;
import cn.org.atool.fluent.mybatis.annotation.GmtCreate;
import cn.org.atool.fluent.mybatis.annotation.GmtModified;
import cn.org.atool.fluent.mybatis.annotation.LogicDelete;
import cn.org.atool.fluent.mybatis.annotation.TableField;
import cn.org.atool.fluent.mybatis.annotation.TableId;
import cn.org.atool.fluent.mybatis.base.RichEntity;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * YourTableEntity: 数据映射实体定义
 *
 * @author Powered By Fluent Mybatis
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Data
@Accessors(
    chain = true
)
@EqualsAndHashCode(
    callSuper = false
)
@AllArgsConstructor
@NoArgsConstructor
@FluentMybatis(
    table = "your_table",
    schema = "test"
)
public class YourTableEntity extends RichEntity {
  private static final long serialVersionUID = 1L;

  @TableId(
      value = "id",
      desc = "主键ID"
  )
  private Long id;

  @TableField(
      value = "age",
      desc = "年龄"
  )
  private Integer age;

  @TableField(
      value = "email",
      desc = "邮箱"
  )
  private String email;

  @TableField(
      value = "name",
      desc = "姓名"
  )
  private String name;

  @TableField(
      value = "gmt_create",
      insert = "now()",
      desc = "记录创建时间"
  )
  @GmtCreate
  private Date gmtCreate;

  @TableField(
      value = "gmt_modified",
      insert = "now()",
      update = "now()",
      desc = "记录最后修改时间"
  )
  @GmtModified
  private Date gmtModified;

  @TableField(
      value = "is_deleted",
      insert = "0",
      desc = "逻辑删除标识"
  )
  @LogicDelete
  private Boolean isDeleted;

  @Override
  public final Class entityClass() {
    return YourTableEntity.class;
  }
}

生成的Dao文件,引用到了YourTableBaseDao类,这个类需要根据Entity类编译生成,在重新编译前会有编译错误,所以生成代码后需要重新Rebuild下

image.png image.png

在Rebuild后,会在target目录下就会多出几个文件, 重新刷新一下工程把target/generated-sources加到源目录上即可。
这些文件时生成在target/generated-sources, 代码中时可以直接引用和打包的,不需要拷贝到src目录下,也不需要维护这些代码,Entity如果发生变化,重新编译打包即可


image.png

启动springboot测试验证效果
这时工程已经具备了fluent mybatis强大的增删改查功能了。我们创建与讴歌测试类来验证一下,在测试类中注入YourMapper,这里演示一个查询所有的方法,所有使用了listEntity,其参数是一个Query对象。


image.png

package com.taotao.fluentmybatisdocs.controller;

import com.taotao.fluentmybatisdocs.entity.YourTableEntity;
import com.taotao.fluentmybatisdocs.mapper.YourTableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @program: fluent-mybatis-docs
 * @ClassName YourTableController
 * @description:
 * @author: wangjin
 * @create: 2023-07-31 09:16
 * @Version 1.0
 **/
@RestController
public class YourTableController {

    @Autowired
    private YourTableMapper yourTableMapper;

    @RequestMapping("/query")
    public List query(YourTableEntity entity) {
        List<YourTableEntity> list = yourTableMapper.listEntity(yourTableMapper.query());
        return list;
    }

}

启动类:

package com.taotao.fluentmybatisdocs;

import cn.org.atool.fluent.mybatis.spring.MapperFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@MapperScan("com.taotao.fluentmybatisdocs.mapper")

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

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

}


你可以手工往数据库中插入几条记录,验证一下效果。

Entity对应的Mapper提供的数据操作方法

相关文章

  • MyBatis学习(转载链接)

    MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql MyBatis学习 ...

  • Spring系列 | 小荷才露尖尖角

    MyBatis学习笔记 MyBatis操练 MyBatis源码 SpringMVC学习笔记 SpringMVC...

  • MyBatis缓存和注解

    Mybatis缓存和注解 学习目标 1、mybatis缓存 2、mybatis注解 学习内容 1、mybatis缓...

  • Mybatis 动态SQL编写

    Mybatis学习 mybatis http://www.mybatis.org/mybatis-3/zh/ind...

  • MyBatis

    MyBatis学习总结(一)——MyBatis快速入门 超详细MyBatis入门讲解

  • MyBatis缓存

    MyBatis Mybatis笔记连载上篇连接Mybatis简单操作学习 Mybatis笔记连载下篇连接Mybat...

  • Mybatis快速入门

    Mybatis 学习内容 Mybatis框架的简单入门 Mybatis框架基本的使用 Mybatis框架的深入和多...

  • Mybatis 学习笔记

    Mybatis 学习笔记 配置 MyBatis 环境 导入MyBaits依赖jar包 要使用 MyBatis, 需...

  • 1.Mybatis - 搭建

    参考 Mybatis 官方 MyBatis学习总结(一)——MyBatis快速入门 安装 说明基于Maven 步骤...

  • MyBatis概述

    【目录】1 什么是MyBatis2 为什么要使用MyBatis3 MyBatis学习路线 1 什么是MyBatis...

网友评论

      本文标题:14 学习 flunet mybatis

      本文链接:https://www.haomeiwen.com/subject/llylpdtx.html