Fluent MyBatis使用入门

您所在的位置:网站首页 fluent的名词怎么写 Fluent MyBatis使用入门

Fluent MyBatis使用入门

2023-10-17 07:58| 来源: 网络整理| 查看: 265

引言

Java中常用的ORM框架主要是mybatis, hibernate, JPA等框架。 国内又以Mybatis用的多,基于mybatis上的增强框架,又有mybatis plus和TK mybatis等。 今天我们介绍一个新的mybatis增强框架 fluent mybatis, 那既然JDBC --> Mybatis或Mybatis Plus无疑简化了开发者的工作,而今天我们所讲的 Fluent MyBatis又起到什么作用呢?

Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比

FluentMybatis原理

初识Fluent MyBatis

Fluent MyBatis是一个 MyBatis 的增强工具,他只做了mybatis的语法糖封装,没有对mybatis做任何修改。 通过编译手段,提供了一系列辅助类来帮助开发简化开发、提高效率。

入门初体验

创建一个示例的数据库表

DROP TABLE IF EXISTS `your_table`; create table `your_table` ( id bigint auto_increment comment '主键ID' primary key, name varchar(30) charset utf8 null comment '姓名', age int null comment '年龄', email varchar(50) charset utf8 null comment '邮箱', gmt_create datetime null comment '记录创建时间', gmt_modified datetime null comment '记录最后修改时间', is_deleted tinyint(2) default 0 null comment '逻辑删除标识' ); 初始化 SpringBoot 项目 设置项目依赖 spring boot: 基于spring boot开发,肯定是必须的 lombok: 省略get, set, toString代码的神器,个人比较喜欢;你也可以手动生成get set方法 mysql-connector-java: 数据库驱动 fluent-mybatis: fluent-mybatis运行时依赖 fluent-mybatis-processor: fluent-mybatis代码生成&编译时依赖 测试依赖的jar包: spring-test, junit

maven pom具体配置

配置数据库信息 spring.datasource.username=root spring.datasource.password=password spring.datasource.url=jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.jdbc.Driver

properties具体配置

创建实体类

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

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

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

public class AppEntityGenerator { static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8"; public static void main(String[] args) { FileGenerator.build(Abc.class); } @Tables( /** 数据库连接信息 **/ url = url, username = "root", password = "password", /** Entity类parent package路径 **/ basePack = "cn.org.fluent.mybatis.springboot.demo", /** Entity代码源目录 **/ srcDir = "spring-boot-demo/src/main/java", /** Dao代码源目录 **/ daoDir = "spring-boot-demo/src/main/java", /** 如果表定义记录创建,记录修改,逻辑删除字段 **/ gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted", /** 需要生成文件的表 **/ tables = @Table(value = {"your_table"}) ) static class Abc { } }

具体代码

这里有3个特殊字段

gmt_create, 记录创建时间,会设置记录插入的默认值,对应生成Entity字段上的注解 @TableField(insert="now()") gmt_modified, 记录最后更新时间,会设置记录插入和更新默认值,对应生成代码Entity字段上注解 @TableField(insert="now()", update="now()") is_deleted, 记录逻辑删除标识,字段类型为Boolean,且设置记录插入的默认值,对应注解 @TableField(insert="0")

执行生成代码main函数, 在工程main/src/java目录下产出 Entity, DaoIntf, DaoImpl文件; 观察YourEntity的主键 id, gmt_create, gmt_modified, is_deleted这几个字段的注解

@Data @Accessors(chain = true) @FluentMybatis(table = "your_table") public class YourEntity extends RichEntity{ private static final long serialVersionUID = 1L; @TableId(value = "id") private Long id; @TableField(value = "gmt_create", insert = "now()") private Date gmtCreate; @TableField(value = "gmt_modified", insert = "now()", update = "now()") private Date gmtModified; @TableField(value = "is_deleted", insert = "0") private Boolean isDeleted; @TableField(value = "age") private Integer age; @TableField(value = "email") private String email; @TableField(value = "name") private String name; @Override public final Class entityClass() { return YourEntity.class; } }

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

@Repository public class YourDaoImpl extends YourBaseDao implements YourDao { // 在这里添加你自己的业务逻辑代码 }

-w100

在Rebuild后,会在target目录下就会多出几个文件, 重新刷新一下工程把target/generated-sources加到源目录上即可。

这些文件时生成在target/generated-sources, 代码中时可以直接引用和打包的,不需要拷贝到src目录下,也不需要维护这些代码,Entity如果发生变化,重新编译打包即可

image.png

启动SpringBoot测试,验证效果

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

@SpringBootTest(classes = QuickStartApplication.class) public class FluentMybatisApplicationTest { @Autowired private YourMapper yourMapper; @Test void contextLoads() { List list = yourMapper.listEntity(yourMapper.query()); for (YourEntity entity : list) { System.out.println(entity); } } }

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

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

下面我们分别介绍FluentMybatis提供的insert, select, update和delete方法,内容的介绍基本按4部分解析

方法的Mapper定义(编译生成的代码) Mapper对应的动态SQL组装SQLProvider(编译生成的代码) 一个验证测试例子 根据例子打印的SQL语句和信息输出,对照查看 FluentMybatis提供的insert方法 insert

单条插入操作

Mapper方法 public interface YourMapper extends IEntityMapper { /** * 插入一条记录 * * @param entity * @return */ @Override @InsertProvider( type = YourSqlProvider.class, method = "insert" ) @Options( useGeneratedKeys = true, keyProperty = "id", keyColumn = "id" ) int insert(YourEntity entity); } 动态SQL组装 public class YourSqlProvider { public String insert(YourEntity entity) { assertNotNull("entity", entity); MapperSql sql = new MapperSql(); sql.INSERT_INTO("your_table"); List columns = new ArrayList(); List values = new ArrayList(); if (entity.getId() != null) { columns.add("id"); values.add("#{id}"); } columns.add("gmt_create"); if (entity.getGmtCreate() != null) { values.add("#{gmtCreate}"); } else { values.add("now()"); } columns.add("gmt_modified"); if (entity.getGmtModified() != null) { values.add("#{gmtModified}"); } else { values.add("now()"); } columns.add("is_deleted"); if (entity.getIsDeleted() != null) { values.add("#{isDeleted}"); } else { values.add("0"); } if (entity.getAge() != null) { columns.add("age"); values.add("#{age}"); } if (entity.getEmail() != null) { columns.add("email"); values.add("#{email}"); } if (entity.getName() != null) { columns.add("name"); values.add("#{name}"); } sql.INSERT_COLUMNS(columns); sql.VALUES(); sql.INSERT_VALUES(values); return sql.toString(); } }

组装过程中,对对应了 @TableField(insert="默认值")的3个字段:gmt_crate, gmt_modified, is_deleted做了特殊判断。

编写insert test验证下 @SpringBootTest(classes = QuickStartApplication.class) public class FluentMybatisApplicationTest { @Autowired private YourMapper yourMapper; @Test void insert() { // 构造一个对象 YourEntity entity = new YourEntity(); entity.setName("Fluent Mybatis"); entity.setAge(1); entity.setEmail("[email protected]"); entity.setIsDeleted(false); // 插入操作 int count = yourMapper.insert(entity); System.out.println("count:" + count); System.out.println("entity:" + entity); } } 执行insert测试方法, 查看控制台输出log信息 DEBUG - ==> Preparing: INSERT INTO your_table(gmt_create, gmt_modified, is_deleted, age, email, name) VALUES (now(), now(), ?, ?, ?, ?) DEBUG - ==> Parameters: false(Boolean), 1(Integer), [email protected](String), Fluent Mybatis(String) DEBUG - 0) { sql.APPEND(", "); } sql.INSERT_VALUES( "#{list[" + index + "].id}", entities.get(index).getGmtCreate() == null ? "now()" : "#{list[" + index + "].gmtCreate}", entities.get(index).getGmtModified() == null ? "now()" : "#{list[" + index + "].gmtModified}", entities.get(index).getIsDeleted() == null ? "0" : "#{list[" + index + "].isDeleted}", "#{list[" + index + "].age}", "#{list[" + index + "].email}", "#{list[" + index + "].name}" ); } return sql.toString(); } }

SQL构造语句是通过一个for循环遍历实体列表,构造出下列SQL语句, 其中对有insert默认值属性处理方式同单条insert一样, 这里就不再重复。

INSERT INTO your_table ('Entity对应的字段列表') VALUES ('实例1值'), ('实例2值') 写个测试看看具体效果 @SpringBootTest(classes = QuickStartApplication.class) public class FluentMybatisApplicationTest { @Autowired private YourMapper yourMapper; void insertBatch(){ List entities = new ArrayList(); entities.add(new YourEntity().setName("Fluent Mybatis").setEmail("[email protected]")); entities.add(new YourEntity().setName("Fluent Mybatis Demo").setEmail("[email protected]")); entities.add(new YourEntity().setName("Test4J").setEmail("[email protected]")); int count = yourMapper.insertBatch(entities); System.out.println("count:" + count); System.out.println("entity:" + entities); } } 执行测试,查看控制台输出 DEBUG - ==> Preparing: INSERT INTO your_table(id, gmt_create, gmt_modified, is_deleted, age, email, name) VALUES (?, now(), now(), 0, ?, ?, ?) , (?, now(), now(), 0, ?, ?, ?) , (?, now(), now(), 0, ?, ?, ?) DEBUG - ==> Parameters: null, null, [email protected](String), Fluent Mybatis(String), null, null, [email protected](String), Fluent Mybatis Demo(String), null, null, [email protected](String), Test4J(String) DEBUG - Preparing: SELECT id, gmt_create, gmt_modified, is_deleted, age, email, name FROM your_table WHERE id = ? DEBUG - ==> Parameters: 8(Long) DEBUG - Preparing: SELECT id, gmt_create, gmt_modified, is_deleted, age, email, name FROM your_table WHERE id IN (?, ?) DEBUG - ==> Parameters: 8(Long), 9(Long) DEBUG - Preparing: SELECT id, gmt_create, gmt_modified, is_deleted, age, email, name FROM your_table WHERE id = ? DEBUG - ==> Parameters: 4(Long) DEBUG - Preparing: SELECT id, gmt_create, gmt_modified, is_deleted, age, email, name FROM your_table WHERE name = ? DEBUG - ==> Parameters: Fluent Mybatis(String) DEBUG - Preparing: SELECT id, gmt_create, gmt_modified, is_deleted, age, email, name FROM your_table WHERE is_deleted = ? AND name = ? DEBUG - ==> Parameters: false(Boolean), Fluent Mybatis(String) DEBUG - Preparing: SELECT name, age, email FROM your_table WHERE id < ? AND name LIKE ? ORDER BY id DESC DEBUG - ==> Parameters: 6(Long), %Fluent%(String) DEBUG - Preparing: SELECT name, age, email AS EMail FROM your_table WHERE id < ? AND name LIKE ? ORDER BY id DESC DEBUG - ==> Parameters: 6(Long), %Fluent%(String) DEBUG - Preparing: SELECT name, age, email AS EMail FROM your_table WHERE id < ? AND name LIKE ? ORDER BY id DESC DEBUG - ==> Parameters: 6(Long), %Fluent%(String) DEBUG - Preparing: SELECT COUNT(*) FROM your_table WHERE id < ? AND name LIKE ? LIMIT ?, ? DEBUG - ==> Parameters: 1000(Long), %Fluent%(String), 0(Integer), 10(Integer) DEBUG - Preparing: SELECT COUNT(*) FROM your_table WHERE id < ? AND name LIKE ? DEBUG - ==> Parameters: 1000(Long), %Fluent%(String) DEBUG - Preparing: UPDATE your_table SET gmt_modified = now(), name = ? WHERE id = ? DEBUG - ==> Parameters: Powerful Fluent Mybatis(String), 2(Long) DEBUG - Preparing: UPDATE your_table SET gmt_modified = now(), name = ?, email = ?, age = ? WHERE id = ? DEBUG - ==> Parameters: Powerful Fluent mybatis(String), [email protected](String), 1(Integer), 2(Integer) DEBUG - Preparing: DELETE FROM your_table WHERE id = ? DEBUG - ==> Parameters: 3(Long) DEBUG - Preparing: DELETE FROM your_table WHERE id IN (?, ?, ?) DEBUG - ==> Parameters: 1(Long), 2(Long), 3(Long) delete

delete, 按自定义Query条件删除记录

Mapper定义 public interface YourMapper extends IEntityMapper { @DeleteProvider( type = YourSqlProvider.class, method = "delete" ) int delete(@Param(Param_EW) IQuery wrapper); }

入参是一个IQuery对象,出参是删除记录数

验证示例 @SpringBootTest(classes = QuickStartApplication.class) public class FluentMybatisApplicationTest { @Autowired private YourMapper yourMapper; @Test void delete() { int count = yourMapper.delete(new YourQuery() .where.id().in(new int[]{1, 2, 3}).end() ); System.out.println("count:" + count); } } 查看控制台输出 DEBUG - ==> Preparing: DELETE FROM your_table WHERE id IN (?, ?, ?) DEBUG - ==> Parameters: 1(Integer), 2(Integer), 3(Integer) DEBUG - Preparing: DELETE FROM your_table WHERE name = ? AND email = ? DEBUG - ==> Parameters: Fluent Mybatis(String), [email protected](String) DEBUG -


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3