<返回更多

hutool-db实现多数据源配置

2022-12-19  今日头条  IT技术分享社区
加入收藏


 

我们在日常开发中,经常会用到一个系统需要链接多个数据库来实现业务的需求,比如多个系统之间数据调用、两个数据之间同步等等。

今天给大家分享使用Hutool-db实现多数据源配置,大家一起来学习一下吧!

1、hutool-db介绍

Hutool-db是一个在JDBC基础上封装的数据库操作工具类,通过包装,使用ActiveRecord思想操作数据库。在Hutool-db中,使用Entity(本质上是个Map)代替Bean来使数据库操作更加灵活,同时提供Bean和Entity的转换提供传统ORM的兼容支持。


 

1. 数据源 DataSource

2. SQL执行器 SQLExecutor

3. CRUD的封装 Db、sqlConnRunner SqlRunner

4. 支持事务的CRUD封装 Session

5. 各种结果集处理类 handler

6. 数据库的一些工具方法汇总 DbUtil

2、新建一个Maven项目2.1 导入依赖包

MySQLmysql-connector-JAVA5.1.45com.microsoft.SqlServersqljdbc44.0cn.hutoolhutool-db5.7.22com.alibabadruid1.2.92.2 新建db.setting配置文件

src/main/resources/config/db.setting

[mysql]url = jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=utf-8&useSSL=false&serverTimezone=GMTusername = rootpassword = 123456driver = com.mysql.jdbc.Driver[sqlserver]url = jdbc:sqlserver://192.168.33.4:1433;DatabaseName=DBusername = sapassword = 123456driver = com.microsoft.sqlserver.jdbc.SQLServerDriver2.3 新建测试demo

* 测试mysqlprivate static void testMysql() {DataSource ds = DSFactory.get("mysql");Db.use(ds);Connection conn = null;try {conn = ds.getConnection();// 插入语句SqlExecutor.execute(conn, "insert into t_user (name,age) value ('小张',35)");// 更新语句SqlExecutor.execute(conn, "update t_user set name='小明002' where id=2 ");// 删除语句SqlExecutor.execute(conn, "delete from t_user where id=2 ");List entityList = SqlExecutor.query(conn, "select * from t_user limit 50", new EntityListHandler());for (Entity entity : entityList) {System.out.println(entity.get("name"));} catch (SQLException e) {} finally {DbUtil.close(conn);* 测试sqlserverprivate static void testSqlServer() {DataSource ds = DSFactory.get("sqlserver");Connection conn = null;try {conn = ds.getConnection();List entityList = SqlExecutor.query(conn, "select * from t_user", new EntityListHandler());for (Entity entity : entityList) {System.out.println(entity.get("username"));} catch (SQLException e) {} finally {DbUtil.close(conn);* 直接代码写jdbc数据源 不推荐的方式private static void testDefineJdbc() {DruidDataSource ds = new DruidDataSource();ds.setUrl("jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT");ds.setUsername("root");ds.setPassword("12345678");Connection conn = null;try {conn = ds.getConnection();List entityList = SqlExecutor.query(conn, "select * from t_user", new EntityListHandler());for (Entity entity : entityList) {System.out.println(entity.get("name"));} catch (SQLException e) {} finally {DbUtil.close(conn);

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>