使用JDBC操作數據庫(JdbcTemplate)
7.1 工程文件中追加使用JDBC的依賴包:pom.xml
<!-- 導入使用JDBC訪問數據庫的依賴包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
添加上述配置後保存,STS會自動下載對應的包文件。
7.2 配置數據源
application.properties配置MySQL數據源。
server.servlet.context-path=/gavin
server.port=9001
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://rm-wz98XXXXuo.mysql.rds.aliyuncs.com:3306/usermng?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=gavin
spring.datasource.password=gavinpw
注意:現在有些文章中可能存在記述錯誤的地方。
spring.datasource.driverClassName
如果設定爲:com.mysql.jdbc.Driver
,會引起編譯錯誤,給出的提示中已經說明了修改方法,將ClassName變更爲:com.mysql.cj.jdbc.Driver
。
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
全局配置文件 application.properties中spring.datasource下只配置了數據庫地址、連接驅動、賬號、密碼,默認使用的是HikariDataSource數據源(com.zaxxer.hikari.HikariDataSource
)。
7.3 代碼測試
創建一個UserController來進行相應的測試。
package com.gavinbj.confmng.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gavinbj.confmng.persistence.entity.UserInfo;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
JdbcTemplate jdbcTemplate;
/**
* TODO:此處爲了方便在瀏覽器確認,直接使用GET插入固定數據,主要爲了體現JDBC的操作方式
*/
@GetMapping("/save")
public String saveUserInfo() {
String sqlInsert = "INSERT INTO user_info (`user_id`, `user_name`, `introduce`, `mobilephone`, `email`, `birthday`, `gender`) VALUES ('gavin', '蓋文', '大學教授', '13940981276', '[email protected]', '2019-10-07', '男')";
int rows = jdbcTemplate.update(sqlInsert);
return "執行成功,添加" + rows + "行";
}
@GetMapping("/{userId}")
public UserInfo getUserById(@PathVariable("userId") String userId) {
String sql = "SELECT * FROM user_info WHERE user_id = ?";
UserInfo user = jdbcTemplate.queryForObject(sql, new Object[] { userId },
new BeanPropertyRowMapper<>(UserInfo.class));
return user;
}
}
插入成功後,進行檢索,檢索結果如下:
{
"userId": "gavin",
"userName": "蓋文",
"introduce": "大學教授",
"mobilephone": "13940981276",
"email": "[email protected]",
"birthday": "2019-10-06T16:00:00.000+0000",
"gender": "男"
}