经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
FluentMybatis实现mybatis动态sql拼装和fluent api语法
来源:jb51  时间:2021/8/4 17:56:01  对本文有异议

开始第一个例子: Hello World

 新建Java工程,设置maven依赖

新建maven工程,设置项目编译级别为Java8及以上,引入fluent mybatis依赖包。

  1. <dependencies>
  2. <!-- 引入fluent-mybatis 运行依赖包, scope为compile -->
  3. <dependency>
  4. <groupId>com.github.atool</groupId>
  5. <artifactId>fluent-mybatis</artifactId>
  6. <version>1.3.1</version>
  7. </dependency>
  8. <!-- 引入fluent-mybatis-processor, scope设置为provider 编译需要,运行时不需要 -->
  9. <dependency>
  10. <groupId>com.github.atool</groupId>
  11. <artifactId>fluent-mybatis-processor</artifactId>
  12. <version>1.3.1</version>
  13. </dependency>
  14. </dependencies>

新建演示用的数据库结构

  1. create schema fluent_mybatis_tutorial;
  2.  
  3. create table hello_world
  4. (
  5. id bigint unsigned auto_increment primary key,
  6. say_hello varchar(100) null,
  7. your_name varchar(100) null,
  8. gmt_create datetime DEFAULT NULL COMMENT '创建时间',
  9. gmt_modified datetime DEFAULT NULL COMMENT '更新时间',
  10. is_deleted tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除'
  11. ) ENGINE = InnoDB
  12. CHARACTER SET = utf8 comment '简单演示表';

创建数据库表对应的Entity类

创建数据库表对应的Entity类: HelloWorldEntity, 你只需要简单的做3个动作:

  • 根据驼峰命名规则命名Entity类和字段
  • HelloWorldEntity继承IEntity接口类
  • 在HelloWorldEntity类上加注解 @FluentMybatis
  1. @FluentMybatis
  2. public class HelloWorldEntity implements IEntity {
  3. private Long id;
  4.  
  5. private String sayHello;
  6.  
  7. private String yourName;
  8.  
  9. private Date gmtCreate;
  10.  
  11. private Date gmtModified;
  12.  
  13. private Boolean isDeleted;
  14. // get, set, toString 方法
  15. }

很简单吧,在这里,你即不需要配置任何mybatis xml文件, 也不需要写任何Mapper接口, 但你已经拥有了强大的增删改查的功能,并且是Fluent API,让我们写一个测试来见证一下Fluent Mybatis的魔法力量!

运行测试来见证Fluent Mybatis的神奇

为了运行测试, 我们还需要进行JUnit和Spring Test相关配置。

配置spring bean定义

 数据源DataSource配置
mybatis的mapper扫描路径
mybatis的SqlSessionFactoryBean

  1. @ComponentScan(basePackages = "cn.org.atool.fluent.mybatis.demo1")
  2. @MapperScan("cn.org.atool.fluent.mybatis.demo1.entity.mapper")
  3. @Configuration
  4. public class HelloWorldConfig {
  5. /**
  6. * 设置dataSource属性
  7. *
  8. * @return
  9. */
  10. @Bean
  11. public DataSource dataSource() {
  12. BasicDataSource dataSource = new BasicDataSource();
  13. dataSource.setDriverClassName("com.mysql.jdbc.Driver");
  14. dataSource.setUrl("jdbc:mysql://localhost:3306/fluent_mybatis_tutorial?useUnicode=true&characterEncoding=utf8");
  15. dataSource.setUsername("root");
  16. dataSource.setPassword("password");
  17. return dataSource;
  18. }
  19.  
  20. /**
  21. * 定义mybatis的SqlSessionFactoryBean
  22. *
  23. * @param dataSource
  24. * @return
  25. */
  26. @Bean
  27. public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
  28. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  29. bean.setDataSource(dataSource);
  30. return bean;
  31. }
  32. }

使用Junit4和Spring-test来执行测试

  • 使用spring-test初始化spring容器
  • 注入HelloWorldEntity对应的Mapper类: HelloWorldMapper, 这个类是fluent mybatis编译时生成的。
  • 使用HelloWorldMapper进行删除、插入、查询、修改操作。
  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = HelloWorldConfig.class)
  3. public class HelloWorldTest {
  4. /**
  5. * fluent mybatis编译时生成的Mapper类
  6. */
  7. @Autowired
  8. HelloWorldMapper mapper;
  9.  
  10. @Test
  11. public void testHelloWorld() {
  12. /**
  13. * 为了演示方便,先删除数据
  14. */
  15. mapper.delete(mapper.query()
  16. .where.id().eq(1L).end());
  17. /**
  18. * 插入数据
  19. */
  20. HelloWorldEntity entity = new HelloWorldEntity();
  21. entity.setId(1L);
  22. entity.setSayHello("hello world");
  23. entity.setYourName("fluent mybatis");
  24. entity.setIsDeleted(false);
  25. mapper.insert(entity);
  26. /**
  27. * 查询 id = 1 的数据
  28. */
  29. HelloWorldEntity result1 = mapper.findOne(mapper.query()
  30. .where.id().eq(1L).end());
  31. /**
  32. * 控制台直接打印出查询结果
  33. */
  34. System.out.println("1. HelloWorldEntity:" + result1.toString());
  35. /**
  36. * 更新id = 1的记录
  37. */
  38. mapper.updateBy(mapper.updater()
  39. .update.sayHello().is("say hello, say hello!")
  40. .set.yourName().is("fluent mybatis is powerful!").end()
  41. .where.id().eq(1L).end()
  42. );
  43. /**
  44. * 查询 id = 1 的数据
  45. */
  46. HelloWorldEntity result2 = mapper.findOne(mapper.query()
  47. .where.sayHello().like("hello")
  48. .and.isDeleted().eq(false).end()
  49. .limit(1)
  50. );
  51. /**
  52. * 控制台直接打印出查询结果
  53. */
  54. System.out.println("2. HelloWorldEntity:" + result2.toString());
  55. }
  56. }

执行Junit4测试方法,控制台输出

1. HelloWorldEntity:HelloWorldEntity{id=1, sayHello='hello world', yourName='fluent mybatis', gmtCreate=null, gmtModified=null, isDeleted=false}
2. HelloWorldEntity:HelloWorldEntity{id=1, sayHello='say hello, say hello!', yourName='fluent mybatis is powerful!', gmtCreate=null, gmtModified=null, isDeleted=false}

神奇吧! 我们再到数据库中查看一下结果

在这里插入图片描述

现在,我们已经通过一个简单例子演示了fluent mybatis的强大功能,
在进一步介绍fluent mybatis更强大功能前,我们揭示一下为啥我们只写了一个数据表对应的Entity类,
却拥有了一系列增删改查的数据库操作方法。

fluent mybatis根据Entity类上@FluentMybatis注解在编译时,
会在target目录class目录下自动编译生成一系列文件:

在这里插入图片描述

核心接口类, 使用时需要了解

  • mapper/*Mapper: mybatis的Mapper定义接口, 定义了一系列通用的数据操作接口方法。
  • dao/*BaseDao: Dao实现基类, 所有的DaoImpl都继承各自基类
  • 根据分层编码的原则,我们不会在Service类中直接使用Mapper类,而是引用Dao类。我们在Dao实现类中根据条件实现具体的数据操作方法。
  • wrapper/*Query: fluent mybatis核心类, 用来进行动态sql的构造, 进行条件查询。
  • wrapper/*Updater: fluent mybatis核心类, 用来动态构造update语句。
  • entity/*EntityHelper: Entity帮助类, 实现了Entity和Map的转换方法
  • 辅助实现时, 实现fluent mybatis动态sql拼装和fluent api时内部用到的类,使用时无需了解
  • 在使用上,我们主要会接触到上述5个生成的java类。Fluent Mybatis为了实现动态拼接和Fluent API功能,还生成了一系列辅助类。
  • helper/*Mapping: 表字段和Entity属性映射定义类
  • helper/*SqlProviderP: Mapper接口动态sql提供者
  • helper/*WrapperHelper: Query和Updater具体功能实现, 包含几个实现:select, where, group by, having by, order by, limit

Fluent Mybatis文档&示例

Fluent Mybatis源码, github

到此这篇关于FluentMybatis实现mybatis动态sql拼装和fluent api语法的文章就介绍到这了,更多相关FluentMybatis实现mybatis动态sql内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号