我們在日常開發(fā)中,經(jīng)常會用到一個系統(tǒng)需要鏈接多個數(shù)據(jù)庫來實現(xiàn)業(yè)務(wù)的需求,比如多個系統(tǒng)之間數(shù)據(jù)調(diào)用、兩個數(shù)據(jù)之間同步等等。
今天給大家分享使用Hutool-db實現(xiàn)多數(shù)據(jù)源配置,大家一起來學(xué)習(xí)一下吧!
1、hutool-db介紹
Hutool-db是一個在JDBC基礎(chǔ)上封裝的數(shù)據(jù)庫操作工具類,通過包裝,使用ActiveRecord思想操作數(shù)據(jù)庫。在Hutool-db中,使用Entity(本質(zhì)上是個Map)代替Bean來使數(shù)據(jù)庫操作更加靈活,同時提供Bean和Entity的轉(zhuǎn)換提供傳統(tǒng)ORM的兼容支持。
1. 數(shù)據(jù)源 DataSource
2. SQL執(zhí)行器 SQLExecutor
3. CRUD的封裝 Db、sqlConnRunner SqlRunner
4. 支持事務(wù)的CRUD封裝 Session
5. 各種結(jié)果集處理類 handler
6. 數(shù)據(jù)庫的一些工具方法匯總 DbUtil
2、新建一個Maven項目2.1 導(dǎo)入依賴包
MySQLmysql-connector-JAVA5.1.45com.microsoft.SqlServersqljdbc44.0cn.hutoolhutool-db5.7.22com.alibabadruid1.2.9
2.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.SQLServerDriver
2.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數(shù)據(jù)源 不推薦的方式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);