在我们日常开发中,经常会用到一个系统需要链接多个数据库来满足业务需求,比如多个系统之间的数据调用,两个数据同步等等。今天分享给大家使用Hutool-db实现多数据源配置,一起学习吧!一、hutool-db简介hutool-db是一个在JDBC基础上封装的数据库操作工具类。通过封装,它使用了ActiveRecord的思想来操作数据库。在Hutool-db中,使用Entity(本质上是一个Map)代替Bean,使数据库操作更加灵活,并提供Bean和Entity之间的转换,为传统ORM提供兼容支持。1.数据源DataSource2.SQL执行器SqlExecutor3.CRUD包Db,SqlConnRunnerSqlRunner4。支持事务的CRUD封装Session5。各种结果集处理类handler6。数据库DbUtil2的一些工具和方法总结。新建Maven项目2.1导入依赖包mysqlmysql-connector-java5.1.45com.microsoft.sqlserversqljdbc4<版本>4.0cn.hutoolhutool-db<版本>5.7。22com.alibabadruid1.2.9</version>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。SQLServerDriver2.3newtestdemo/***testmysql*/privatestaticvoidtestMysql(){DataSourceds=DSFactory.get("mysql");Db.use(ds);连接conn=null;尝试{conn=ds.getConnection();//插入语句SqlExecutor.execute(conn,"insertintot_user(name,age)value('XiaoZhang',35)");//更新语句SqlExecutor.execute(conn,"updatet_usersetname='Xiaoming002'whereid=2");//删除语句SqlExecutor.execute(conn,"deletefromt_userwhereid=2");列表<Entity>entityList=SqlExecutor.query(conn,"select*fromt_userlimit50",newEntityListHandler());for(Entityentity:entityList){System.out.println(entity.get("name"));}}catch(SQLExceptione){}最后{DbUtil.close(conn);}}/***测试sqlserver*/privatestaticvoidtestSqlServer(){DataSourceds=DSFactory.get("sqlserver");连接conn=null;尝试{conn=ds.getConnection();ListentityList=SqlExecutor.query(conn,"select*fromt_user",newEntityListHandler());for(Entityentity:entityList){System.out.println(entity.get("username"));}}catch(SQLExceptione){}最后{DbUtil.close(conn);}}/***直接代码编写jdbc数据源不推荐的方式*/privatestaticvoidtestDefineJdbc(){DruidDataSourceds=newDruidDataSource();ds.setUrl("jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=utf-8&useSSL=false&serverTimeznotallow=GMT");ds.setUsername("root");ds.setPassword("12345678");连接conn=null;尝试{conn=ds.getConnection();ListentityList=SqlExecutor.query(conn,"select*fromt_user",newEntityListHandler());for(Entityentity:entityList){System.out.println(entity.get("name"));}}catch(SQLExceptione){}最后{DbUtil.close(conn);}}