介绍
dbVisitor(原HasorDB) 是一个全功能数据库访问工具,提供对象映射、丰富的类型处理、动态SQL、存储过程、 内置分页方言20+、 支持嵌套事务、多数据源、条件构造器、INSERT 策略、多语句/多结果。并兼容 Spring 及 MyBatis 用法。 它不依赖任何其它框架,因此可以很方便的和任意一个框架整合在一起使用。
功能特性
-
熟悉的方式
- JdbcTemplate 接口方式(高度兼容 Spring JDBC)
- Mapper 文件方式(高度兼容 MyBatis)
- LambdaTemplate (高度接近 MyBatis Plus、jOOQ 和 BeetlSQL)
- @Insert、@Update、@Delete、@Query、@Callable 注解(类似 JPA)
-
事务支持
- 支持 5 个事务隔离级别、7 个事务传播行为(与 Spring tx 相同)
- 提供 TransactionTemplate、TransactionManager 接口方式声明式事务控制能力(用法与 Spring 相同)
-
特色优势
- 支持 分页查询 并且提供多种数据库方言(20+)
- 支持 INSERT 策略(INTO、UPDATE、IGNORE)
- 更加丰富的 TypeHandler(MyBatis 40+,HasorDB 60+)
- Mapper XML 支持多语句、多结果
- 提供独特的规则机制,让动态 SQL 更加简单
- 支持 存储过程
- 支持 JDBC 4.2 和 Java8 中时间类型
- 支持多数据源
引入依赖
截止到目前为止 dbVisitor 的最新版本为:4.3.0
- 在 https://mvnrepository.com/artifact/net.hasor/hasor-db 上也可以查询到最新版本
<dependency>
<groupId>net.hasor</groupId>
<artifactId>hasor-db</artifactId>
<version>4.3.0</version>
</dependency>
然后再引入数据库驱动以 MySQL,Maven 方式为例:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
使用 HasorDB 可以不依赖数据库连接池,但有数据库连接池是大多数项目的标配。这里选用 Alibaba 的 Druid
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
最后准备一个数据库表,并初始化一些数据(CreateDB.sql
文件)
drop table if exists `test_user`;
create table `test_user` (
`id` int(11) auto_increment,
`name` varchar(255),
`age` int,
`create_time` datetime,
primary key (`id`)
);
insert into `test_user` values (1, 'mali', 26, now());
insert into `test_user` values (2, 'dative', 32, now());
insert into `test_user` values (3, 'jon wes', 41, now());
insert into `test_user` values (4, 'mary', 66, now());
insert into `test_user` values (5, 'matt', 25, now());
执行 SQL
使用 SQL 的方式读取数据,PrintUtils
和 DsUtils
两个工具类可以在例子工程中找到
// 创建数据源
DataSource dataSource = DsUtils.dsMySql();
// 创建 JdbcTemplate 对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
// 加载测试数据脚本
jdbcTemplate.loadSQL("CreateDB.sql");
// 查询数据并 Map 形式返回
List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from test_user");
// 打印测试数据
PrintUtils.printMapList(mapList);
控制台可以得到如下结果
/--------------------------------------------\
| id | name | age | create_time |
|--------------------------------------------|
| 1 | mali | 26 | 2021-11-12 19:14:06.0 |
| 2 | dative | 32 | 2021-11-12 19:14:06.0 |
| 3 | jon wes | 41 | 2021-11-12 19:14:06.0 |
| 4 | mary | 66 | 2021-11-12 19:14:06.0 |
| 5 | matt | 25 | 2021-11-12 19:14:06.0 |
\-------------------------