對於數據訪問層,無論是SQL還是NOSQL,springboot默認采用整合spring data方式進行統一處理,添加大量自動配置,屏蔽了許多設置,引入各種xxxTemplate,xxxRepository來簡化我們對數據訪問層的操作。對我們來說只需要進行簡單的設置即可。
之前利用VMware安裝了centos7系統,並利用橋接模式實現了主機和虛擬機之間的通信,最后利用docker安裝了Mysql鏡像。這次終於重新又回到了springboot的懷抱中。springboot整合jdbc和數據源真的是一波三折。首先明確我使用的springboot版本是2.2.4。並使用application.yml進行數據庫連接相關配置。
(1)第一波
之前自己通過idea創建過了springboot項目,不想再重新建了,於是想導入jdbc啟動器和mysql驅動,在網上找了一圈都沒找到如何在已經創建好的springboot中繼續添加啟動器,只好自己手動添加。這里就有兩個坑:jdbc啟動器的名字問題、mysql驅動版本與mysql版本問題。最開始,找到的jdbc啟動器是:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
之后進行測試的時候一老報錯:
Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
說是沒有這么一個bean,百度半天也沒有結果,自己只好重新建一個springboot項目,並勾選Mysql driver和data jdbc。然后查看pom.xml文件,發現是:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency>
修改完之后繼續。application.yml中設置Driver的時候,需要注意和自己版本的mysql相對應,而springboo連接Mysql驅動t默認版本是沒指定的,一般是比較新,用Mysql5.7就要指定為mysql-connector-java的版本為5.1.41之類的,而且對應的驅動是com.mysql.jdbc.Driver,最新版本的mysql驅動名稱變了。
(2)第二波
這是自己犯的一個低級錯誤:
Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl
自己再輸入urll時少了mysql后面的冒號:
jdbc:mysql://192.168.124.22:3306/jdbc
(3)第三波
這可不是我的鍋了。在主機連接到虛擬機中linux下的docker中的mysql時,報錯:
java.sql.SQLException: Access denied for user ''@'192.168.124.9' (using password: NO)
百度了下,在application.yml中,因為springboot中默認是data-username和data-password,要改成username和password。這也太坑了。
最后是相關代碼:
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.gong</groupId> <artifactId>springboot-curd</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-curd</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
application.yml
spring: datasource: username: root password: 123456 url: jdbc:mysql://192.168.124.22:3306/jdbc driver-class-name: com.mysql.jdbc.Driver
SpringbootCurdApplicationTests.java
package com.gong.springbootcurd; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootCurdApplicationTests { @Autowired DataSource dataSource; @Test public void contextLoads() { } @Test public void testConnection() throws SQLException { System.out.println(dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); } }
最后是相關輸出:
接下來繼續,我們可以自己讓springboot啟動時運行建表和插入語句,在application.yml中繼續配置:
spring: datasource: username: root password: 123456 url: jdbc:mysql://192.168.124.22:3306/jdbc?serverTimezone=UTC driver-class-name: com.mysql.jdbc.Driver schema: - classpath:department.sql initialization-mode: always
department.sql
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for department -- ---------------------------- DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
啟動springboot之后就會在jdbl數據庫中生成一個department的表,我們在其中添加些數據:
最后利用jdbc進行數據操作:
@Controller public class HelloController { @Autowired JdbcTemplate jdbcTemplate; @ResponseBody @RequestMapping("/query") public Map<String,Object> testJdbc(){ List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department"); return list.get(0); } }
此時記得先注釋掉之前的自動建表配置好,不然我們添加的數據會沒清楚,再啟動服務器:
帶上curd 是因為我在另一個配置文件application.properties中配置了:
server.servlet.context-path=/curd
至此,整合jdbc並操作mysql數據庫就完成了。