SpringBoot整合JDBC、Druid數據源的示例代碼
1.SpringBoot整合JDBCTemplate
1.1.導入jdbc相關依賴包
主要的依賴包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--實現web頁面接口調用--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
1.2.yaml配置數據源
application.yml用于連接jdbc數據庫操作數據源配置,這里是最簡化的配置:
spring: datasource: username: root password: admin #假如時區(qū)報錯,增加時區(qū)配置serverTimezone=UTC,以及編碼配置 url: jdbc:mysql://localhost:3306/mybatis02_0322?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver
實際開發(fā)過程中基本上會與Druid、C3P0整合,下面也給出了整合Druid數據源相關的配置,所以這里一并放上完整的application.yml配置:
spring: datasource: username: root password: admin #假如時區(qū)報錯,增加時區(qū)配置serverTimezone=UTC url: jdbc:mysql://localhost:3306/mybatis02_0322?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #springboot 默認是不注入這些屬性值的,需要自己綁定 #druid 數據源專有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置監(jiān)控統(tǒng)計攔截的filters,stat:監(jiān)控統(tǒng)計、log4j:日志記錄、wall:防止sql注入 #如果允許時報錯:java.lang.ClassNotFoundException:org.apache.log4j.Priority #則導入 log4j 依賴即可,maven地址:https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
最后測試一下數據庫連接訪問是否成功:
@SpringBootTest class SpringbootDataApplicationTests { @Autowired private DataSource dataSource; @Test void testConnection() throws SQLException { System.out.println(dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println(connection); } }
打印成功,顯示獲取到了數據源信息:
1.3.界面訪問接口測試
@RestController public class JDBCController { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping("/queryList") public List<Map<String, Object>> query() { String sql = "select * from user"; List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql); return queryForList; } @RequestMapping("/addUser") public String AddUser(){ String sql = "insert into mybatis02_0322.user(id, username, password) values(4, '李磊', '654321')"; int update = jdbcTemplate.update(sql); return "AddUser Ok"; } @RequestMapping("/update/{id}") public String update(@PathVariable("id") Integer id){ String sql = "update mybatis02_0322.user set username = ?, password = ? where id = " + id; Object[] objects = new Object[2]; objects[0] = "測試哈哈哈111"; objects[1] = "32321"; int update = jdbcTemplate.update(sql, objects); return "updateUser Ok"; } @RequestMapping("/delete/{id}") public String delete(@PathVariable("id") Integer id){ String sql = "delete from mybatis02_0322.user where id = " + id; int update = jdbcTemplate.update(sql); return "delete Ok"; } }
這里對應接口請求頁面進行請求測試即可,后臺數據庫層面進行驗證,比較簡單,這里就不一一細說,對應可以去看我的源碼。
2.SpringBoot整合DruidDataSource
2.1.Druid簡介
Druid是阿里巴巴開源平臺上一個數據庫連接池實現,它結合了C3P0、DBCP、PROXOOL等DB池的優(yōu)秀實踐,同時加入了日志監(jiān)控。
Druid可以很好地監(jiān)控DB池連接和Sql的執(zhí)行情況,是天生針對監(jiān)控的DB連接池。
SpringBoot2.0以上默認使用Hikari數據源,可以說HiKari和Druid都是當前Java Web上開源的優(yōu)秀數據源。
2.2.導入Druid相關依賴
對應pom.xml文件:
<!--整合alibaba druid數據源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.3</version> </dependency> <!--導入log4j日志包--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2.3.配置Druid并使用監(jiān)控頁面
①編寫DruidConfig類,啟用后臺監(jiān)控功能Bean以及過濾器Bean:
@Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource(){ return new DruidDataSource(); } //后臺監(jiān)控功能 @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); //后臺需要有人登陸,賬號密碼配置 HashMap<String, String> initParameters = new HashMap<>(); initParameters.put("loginUsername", "admin"); //登陸key,是固定的 loginUsername loginPassword initParameters.put("loginPassword", "123456"); //允許誰可以訪問 initParameters.put("allow", ""); //禁止誰可以訪問 initParameters.put("fengye", "192.168.1.10"); bean.setInitParameters(initParameters); //設置初始化參數 return bean; } //過濾器 @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(); bean.setFilter(new WebStatFilter()); HashMap<String, String> initParameters = new HashMap<>(); //這些不進行統(tǒng)計 initParameters.put("exclusions", "*.js,*.css,/druid/*"); bean.setInitParameters(initParameters); return bean; } }
②啟動頁面訪問Druid并測試請求訪問sql:
本博客寫作參考文檔相關:
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter
https://www.yuque.com/atguigu/springboot/aob431#wtNk1
Spring Boot 2 學習筆記(上):https://blog.csdn.net/u011863024/article/details/113667634
Spring Boot 2 學習筆記(下):
https://blog.csdn.net/u011863024/article/details/113667946
示例代碼已上傳至Github地址:
https://github.com/devyf/SpringBoot_Study
到此這篇關于SpringBoot整合JDBC、Druid數據源的文章就介紹到這了,更多相關SpringBoot整合JDBC、Druid數據源內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java String類簡單用法實戰(zhàn)示例【字符串輸出、比較】
這篇文章主要介紹了Java String類簡單用法,結合具體實例形式分析了Java使用String類實現字符串的輸出和比較功能相關操作技巧,需要的朋友可以參考下2019-07-07java.lang.NoSuchMethodException: com.sun.proxy.$Proxy58.list
這篇文章主要介紹了java.lang.NoSuchMethodException: com.sun.proxy.$Proxy58.list錯誤解決辦法的相關資料,需要的朋友可以參考下2016-12-12Java利用Dijkstra和Floyd分別求取圖的最短路徑
本文主要介紹了圖的最短路徑的概念,并分別利用Dijkstra算法和Floyd算法求取最短路徑,最后提供了基于鄰接矩陣和鄰接表的圖對兩種算法的Java實現。需要的可以參考一下2022-01-01關于Java單個TCP(Socket)連接發(fā)送多個文件的問題
這篇文章主要介紹了關于Java單個TCP(Socket)連接發(fā)送多個文件的問題,每次我只能使用一個 Socket 發(fā)送一個文件,沒有辦法做到連續(xù)發(fā)送文件,本文來解決這個問題,需要的朋友可以參考下2023-04-04阿里面試Nacos配置中心交互模型是push還是pull原理解析
這篇文章主要為大家介紹了阿里面試Nacos配置中心交互模型是push還是pull原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07